How to read XML file in Java – (DOM Parser)

In this tutorial, we will show you how to read an XML file via DOM XML parser. DOM parser parses the entire XML document and loads it into memory; then models it in a “TREE” structure for easy traversal or manipulation.

In short, it turns a XML file into DOM or Tree structure, and you have to traverse a node by node to get what you want.

What is Node?
In the DOM, everything in an XML document is a node, read this.
Warning
DOM Parser is slow and consumes a lot of memory when it loads an XML document which contains a lot of data. Please consider SAX parser as solution for it, SAX is faster than DOM and use less memory.

1. DOM XML Parser Example

This example shows you how to get the node by “name”, and display the value.

/Users/mkyong/staff.xml

<?xml version="1.0"?>
<company>
	<staff id="1001">
		<firstname>yong</firstname>
		<lastname>mook kim</lastname>
		<nickname>mkyong</nickname>
		<salary>100000</salary>
	</staff>
	<staff id="2001">
		<firstname>low</firstname>
		<lastname>yin fong</lastname>
		<nickname>fong fong</nickname>
		<salary>200000</salary>
	</staff>
</company>
ReadXMLFile.java

package com.mkyong.seo;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

  public static void main(String argv[]) {

    try {

	File fXmlFile = new File("/Users/mkyong/staff.xml");
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	Document doc = dBuilder.parse(fXmlFile);
			
	//optional, but recommended
	//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
	doc.getDocumentElement().normalize();

	System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
			
	NodeList nList = doc.getElementsByTagName("staff");
			
	System.out.println("----------------------------");

	for (int temp = 0; temp < nList.getLength(); temp++) {

		Node nNode = nList.item(temp);
				
		System.out.println("\nCurrent Element :" + nNode.getNodeName());
				
		if (nNode.getNodeType() == Node.ELEMENT_NODE) {

			Element eElement = (Element) nNode;

			System.out.println("Staff id : " + eElement.getAttribute("id"));
			System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
			System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
			System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
			System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

		}
	}
    } catch (Exception e) {
	e.printStackTrace();
    }
  }

}

Result


Root element :company
----------------------------

Current Element :staff
Staff id : 1001
First Name : yong
Last Name : mook kim
Nick Name : mkyong
Salary : 100000

Current Element :staff
Staff id : 2001
First Name : low
Last Name : yin fong
Nick Name : fong fong
Salary : 200000

2. Looping the Node

This example reads the same “staff.xml“, and showing you how to loop the node one by one, and print out the node name and value, and also the attribute if any.

ReadXMLFile2.java

package com.mkyong.seo;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXMLFile2 {

  public static void main(String[] args) {

    try {

	File file = new File("/Users/mkyong/staff.xml");

	DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
                             .newDocumentBuilder();

	Document doc = dBuilder.parse(file);

	System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

	if (doc.hasChildNodes()) {

		printNote(doc.getChildNodes());

	}

    } catch (Exception e) {
	System.out.println(e.getMessage());
    }

  }

  private static void printNote(NodeList nodeList) {

    for (int count = 0; count < nodeList.getLength(); count++) {

	Node tempNode = nodeList.item(count);

	// make sure it's element node.
	if (tempNode.getNodeType() == Node.ELEMENT_NODE) {

		// get node name and value
		System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
		System.out.println("Node Value =" + tempNode.getTextContent());

		if (tempNode.hasAttributes()) {

			// get attributes names and values
			NamedNodeMap nodeMap = tempNode.getAttributes();

			for (int i = 0; i < nodeMap.getLength(); i++) {

				Node node = nodeMap.item(i);
				System.out.println("attr name : " + node.getNodeName());
				System.out.println("attr value : " + node.getNodeValue());

			}

		}

		if (tempNode.hasChildNodes()) {

			// loop again if has child nodes
			printNote(tempNode.getChildNodes());

		}

		System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]");

	}

    }

  }

}

Result :


Root element :company

Node Name =company [OPEN]
Node Value =
	
		yong
		mook kim
		mkyong
		100000
	
	
		low
		yin fong
		fong fong
		200000
	


Node Name =staff [OPEN]
Node Value =
		yong
		mook kim
		mkyong
		100000
	
attr name : id
attr value : 1001

Node Name =firstname [OPEN]
Node Value =yong
Node Name =firstname [CLOSE]

Node Name =lastname [OPEN]
Node Value =mook kim
Node Name =lastname [CLOSE]

Node Name =nickname [OPEN]
Node Value =mkyong
Node Name =nickname [CLOSE]

Node Name =salary [OPEN]
Node Value =100000
Node Name =salary [CLOSE]
Node Name =staff [CLOSE]

Node Name =staff [OPEN]
Node Value =
		low
		yin fong
		fong fong
		200000
	
attr name : id
attr value : 2001

Node Name =firstname [OPEN]
Node Value =low
Node Name =firstname [CLOSE]

Node Name =lastname [OPEN]
Node Value =yin fong
Node Name =lastname [CLOSE]

Node Name =nickname [OPEN]
Node Value =fong fong
Node Name =nickname [CLOSE]

Node Name =salary [OPEN]
Node Value =200000
Node Name =salary [CLOSE]
Node Name =staff [CLOSE]
Node Name =company [CLOSE]
Note
You may interest at this How to get Alexa Ranking In Java. It shows you how to use DOM to parse the Alexa XML result.

References

  1. When to Use DOM
  2. Normalization in DOM parsing with java – how does it work?
  3. Learn XML DOM
  4. What is Node?
  5. What is Element?

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
154 Comment threads
45 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
148 Comment authors
MujahidVarunEyad AymanxXxLa Ra Recent comment authors
newest oldest most voted
pandi
Guest
pandi

what is the use of normalize() please explain about that method?

Varun
Guest
Varun

This basically means that the following XML element
hello
wor
ld

could be represented like this in a DENORMALIZED node:

Element foo
Text node: “”
Text node: “Hello ”
Text node: “wor”
Text node: “ld”

When NORMALIZED, the node will look like this

Element foo
Text node: “Hello world”

Serch
Guest
Serch

TE AMO!!!

Rakesh Sonu
Guest
Rakesh Sonu

boss getTextContent() is throwning an error .May i know what i need to do.

Ionut Popa
Guest
Ionut Popa

Thanks for the tip man!

Asky
Guest
Asky

You are my hero 🙂
Thanks a lot for this.
For simple XML files this is much better than SAX Parser which to say the least is a f****** pain in the a**.

anon
Guest
anon

You may want to look at vtd-xml as the state of the art in XML processing, consuming far less memory than DOM

http://vtd-xml.sf.net

trackback
How to read XML file in Java – (JDOM Example) | Java

[…] P.S You can compare the syntax with SAX and DOM parser in the following two examples – How to read XML file in Java – (SAX Parser) – How to read XML file in Java – (DOM Parser) […]

Benton Comiskey
Guest
Benton Comiskey

I can just say thank you for this wonderful post!

Beginner VB Programmer
Guest
Beginner VB Programmer

‘Visual Basic Module Module1 Sub Main() Dim doc = XDocument.Load(“file.xml”) Console.WriteLine(“Root element :” & doc.Root.Name.ToString) Console.WriteLine(“———————–“) For Each staff In doc… Console.WriteLine(“First Name : ” & staff..Value) Console.WriteLine(“Last Name : ” & staff..Value) Console.WriteLine(“Nick Name : ” & staff..Value) Console.WriteLine(“Salary : ” & staff..Value) Next End Sub End Module

Norman Pfeffer
Guest
Norman Pfeffer

I d like to get a domme like this one ! More posts like this?

trackback
Java XML Tutorials | J2EE Web Development Tutorials

[…] Read XML file – (DOM Parser) Example to read a XML file with DOM parser. […]

trackback
advantage of jaxp over dom and sax parser - Java Forums

[…] any body please tell me the advantage of jaxp over dom and sax parser i had gone through the site How to read XML file in Java – (DOM Parser) How to read XML file in Java – (SAX Parser) but there not defined the jaxp using and jaxb is […]

abiram
Guest
abiram

nice one

Roger
Guest
Roger

Thnaks for the article MkYong, the source explains well how to create an implementation of an XML parsing class, which will come very handy in my current project.
Thanx again…
Roger

Doyle F
Guest
Doyle F

This covers the very simple stuff but how do you get several layers down. for example

0
170
640
1
UINT32
ASCENDING

HOw do you get things like the MIN_VALUE or the TYPE, etc.

Doyle F
Guest
Doyle F

Obviously the xml get stripped out of the message, good going.

fooond
Guest
fooond

i want this code but for general XML not spesific ??

wa
Guest
wa

Thanks Man!

jp
Guest
jp

thank you very much, it was extremely helpful.

Rangalal Gamage
Guest
Rangalal Gamage

You save my time. Thanks a lot.

up
Guest
up

Excellent
Thanks a lot

JL
Guest
JL

Thanks a lot!

Aaron
Guest
Aaron

Simple example, thanks! 🙂

James Watkins
Guest
James Watkins

So many Java tutorials out there are WAY TOO VERBOSE. Thank you for providing an example which can be glanced at to provide a solution. May you set the bar for other tutorial-writers to create such pragmatic examples.

tom3cang
Guest
tom3cang

Thank you, Mkyong! It’s very helpful for me with this sample 🙂

Nathan
Guest
Nathan

AI-SAVE
45000
30/10/2016
0

CI Benefit (Add)
45000
30/10/2013
1

TPD
45000
30/10/2014
1

importPackage(Packages.org.apache.xerces.parsers);
importPackage(Packages.org.xml.sax);
importPackage(Packages.java.io);

var parser = new DOMParser();
parser.parse(new InputSource(new StringReader(dataSetRow[“V_ISSUECONTR_DATA”])));
var nodelist = parser.getDocument().getElementsByTagName(‘/RESULT/MESSAGE/BENEFITS/ROWSET/ROW’);
//var entry = nodelist.item(0).getFirstChild().getNodeValue();
var entry = nodelist.item(0).getFirstChild().getNodeValue();

Can you help me to get the AI-SAVE, above code gives error. Any help ?

Lawrence Lagerlof
Guest
Lawrence Lagerlof

God bless you, mkyong.

Brandon Abbott
Guest
Brandon Abbott

You should slap a license on this code. Preferably Apache 2.0

SRIKANTH
Guest
SRIKANTH

Simple example, thanks! 🙂

Vijeth
Guest
Vijeth

hey,thank u it was really helpful….how to read nested tags??plz help me in this regard.

Vijeth
Guest
Vijeth

xml file is somethng like this

<A>
   <B>
      <b1>
      <b2>
      <B>
         <b1>
         <b2>
       </B>

   </B>
   <B>
      <b1>
      <b2>
   </B>
   -
   - 
   -
   -
</A>

and so on!!

ashadi_iputu
Guest
ashadi_iputu

nice share
thanks

Dhiral
Guest
Dhiral

How to get Attributes name and value useing this parser ???

Life Saviour
Guest
Life Saviour

Description statusCode statusString realizeStatus connect disconnect startServing stopServing package com.foo; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ReadXMLFile { //private iVar private String tName; // Method process reading xml file public void setTagValue(String tagName, String operations){ try { File xmlFile = new File(“ResourcesAttrAndMethod\\AttrAndMethod.xml”); // obtain a parser that produces DOM object trees from XML documents. DocumentBuilderFactory dbFactory = DocumentBuilderFactory .newInstance();// obtain a Parser //Defines the API to obtain DOM Document instances from an XML document DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //The Document interface represents the entire XML document… Read more »

Life Saviour
Guest
Life Saviour

Description
statusCode
statusString

realizeStatus
connect
disconnect
startServing
stopServing

Life Saviour
Guest
Life Saviour
<?xml version="1.0" encoding="UTF-8"?>
<MBeanOperations><!-- Document root node -->

	<!-- List of attributes -->
	<attributes>
		<description>Description</description>
		<statusCode>statusCode</statusCode>
		<statusString>statusString</statusString>
	</attributes>
	
	<!-- List of methods -->
	<operations>
		<realizeStatus>realizeStatus</realizeStatus>
		<connect>connect</connect>
		<disconnect>disconnect</disconnect>
		<startServing>startServing</startServing>
		<stopServing>stopServing</stopServing>		
	</operations>
	
</MBeanOperations>
Life Saviour
Guest
Life Saviour

package com.foo; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ReadXMLFile { //private iVar private String tName; // Method process reading xml file public void setTagValue(String tagName, String operations){ try { File xmlFile = new File("ResourcesAttrAndMethod\\AttrAndMethod.xml"); // obtain a parser that produces DOM object trees from XML documents. DocumentBuilderFactory dbFactory = DocumentBuilderFactory .newInstance();// obtain a Parser //Defines the API to obtain DOM Document instances from an XML document DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //The Document interface represents the entire XML document // provides the primary access to the document's… Read more »

Life Saviour
Guest
Life Saviour
<?xml version="1.0" encoding="UTF-8"?>
<MBeanOperations><!-- Document root node -->

	<!-- List of attributes -->
	<attributes>
		<description>Description</description>
		<statusCode>statusCode</statusCode>
		<statusString>statusString</statusString>
	</attributes>
	
	<!-- List of methods -->
	<operations>
		<realizeStatus>realizeStatus</realizeStatus>
		<connect>connect</connect>
		<disconnect>disconnect</disconnect>
		<startServing>startServing</startServing>
		<stopServing>stopServing</stopServing>		
	</operations>
	
</MBeanOperations>
Life Saviour
Guest
Life Saviour

You can pass any tagName through main() method i.e any tag – operations or attributes etc