How to read XML file in Java – (DOM Parser)
Here’s an example to show you how to read a XML file in Java via DOM XML parser. The DOM interface is the easiest XML parser to understand, and use. It parses an entire XML document and load it into memory, modeling it with Object for easy traversal or manipulation.
DOM Parser is slow and consume a lot of memory if it load a 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 Parser Example
A DOM XML parser read below XML file and print out each elements one by one.
File : file.xml
<?xml version="1.0"?> <company> <staff> <firstname>yong</firstname> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>100000</salary> </staff> <staff> <firstname>low</firstname> <lastname>yin fong</lastname> <nickname>fong fong</nickname> <salary>200000</salary> </staff> </company>
File : ReadXMLFile.java – A Java class to read above XML file.
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("c:\\file.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); 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); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("First Name : " + getTagValue("firstname", eElement)); System.out.println("Last Name : " + getTagValue("lastname", eElement)); System.out.println("Nick Name : " + getTagValue("nickname", eElement)); System.out.println("Salary : " + getTagValue("salary", eElement)); } } } catch (Exception e) { e.printStackTrace(); } } private static String getTagValue(String sTag, Element eElement) { NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes(); Node nValue = (Node) nlList.item(0); return nValue.getNodeValue(); } }
2. Result
Root element :company ----------------------- First Name : yong Last Name : mook kim Nick Name : mkyong Salary : 100000 First Name : low Last Name : yin fong Nick Name : fong fong Salary : 200000
You may interest ath this How to read XML file in Java – (SAX Parser), do compare and spot the different implementation between DOM and SAX parse.







From
Description
statusCode
statusString
realizeStatus
connect
disconnect
startServing
stopServing
I want to extract
Description
statusCode
statusString
Description
statusCode
statusString
remove the tags u do not want mate. :)
XML -
Participating in a race is fun for all. This game helps students to revisit the concept of ordinal numbers each time they identify the winner and the track number.
Ordinal Numbers
how to write java code for this
Hello Sir,
Please tell me how to access bdb tag in this XML.
please help me…
it would be really greatfull!!!!
wanna retrieve data from bdb tag…..
Thanks, was very helpful.
send me the similar code for SAXparser
This was really very nice article, thanks mkyong.
I am having an xml file which is a response returned from webservice , Now I want to parse this file , actually this is a nested tag xml file . Can you please help me out how to get values out of it: xml is attached below:–
I want the following output after parsing:—>
entId=5
productName=Pro_213
FeatureName=F1
userId=aa
startDate=02/01/2012
endateDate=03/30/2012
TotalConsumption=7
usageType=time based
recordCount=1
entId=6
productName=Pro_214
FeatureName=F2
userId=aa
startDate=02/01/2012
endateDate=03/30/2012
TotalConsumption=4
usageType=count based
recordCount=1
can you please help me out on it using dom parser.
Are you gone be reading this data from the client or you want the data to be raw.
Thanks a lot for the useful code.. Am just an amateur in these type of coding. I used ur code in one of my program and tried parsing a XML file… the problem is that my XML has many empty tags and using ur code throws null pointer exception.Pls clarify. I kno tat its a simple issue.. but it may help me a lot!!
Thanks!!!
Can you provide a sample of XML file with many empty tags, so that i can do some testing.
Thanx for this example, but i have a problem. Your program in Eclipse IDE don’t out elements from XML file.
This part of code don’t work :-( I don’t see FirstName, LastName, NickName, Salary
It works for me; maybe your xml tags doesn’t match the elements name your passing my friend. Are you getting nullPointerException?
I have error in program. XML file contents tag. In program i write stuff
send all ur source code including xml file and i,ll check it for u
How to get Attributes name and value useing this parser ???
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
// provides the primary access to the document’s data
org.w3c.dom.Document doc = dBuilder.parse(xmlFile);
//direct access to the child node that is the document element of the document.
doc.getDocumentElement().normalize();
System.out.println(“Root Element: ”
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName(operations);
System.out.println(“=============================”);
// Keep reading elements till you reach the end of subNode i.e – end of tag
for (int i = 0; i < nList.getLength(); i++) {
org.w3c.dom.Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;//get hold of operations tag
// Pass the tagName to method so that it can be papulated
String tagValue = populateTagValue(tagName, eElement);
// Set the fetch tag value for getter method
processXML(tagValue);
}
}
} catch (ParserConfigurationException e) {
System.out.println(e);
} catch (SAXException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}
}
// Method return tagValue fetched from file to its caller
public String populateTagValue(String tName, Element element) {
NodeList nList = element.getElementsByTagName(tName).item(0)
.getChildNodes();
Node nValue = nList.item(0);
return nValue.getNodeValue();
}
// Method Sets the tagName recieved through its param
public void processXML(String tagName){
this.tName = tagName;
}
// Method return tagName to its caller/invoker
public String getTagName(){
return tName;
}
public static void main(String… args) {
ReadXMLFile file = new ReadXMLFile();
file.setTagValue("description", "attributes");
System.out.println(file.getTagName());
}
}
hope his helps
Description
statusCode
statusString
realizeStatus
connect
disconnect
startServing
stopServing
You can pass any tagName through main() method i.e any tag – operations or attributes etc
nice share
thanks
hey,thank u it was really helpful….how to read nested tags??plz help me in this regard.
xml file is somethng like this
<A> <B> <b1> <b2> <B> <b1> <b2> </B> </B> <B> <b1> <b2> </B> - - - - </A>and so on!!
Simple example, thanks! :)
You should slap a license on this code. Preferably Apache 2.0
May i know why should i apply a license for this?
I feel like there could be some copyright issues otherwise? Like, if you really wanted to, you could bar us from referencing this piece, no?
Why you want this code to be not read by others.Its always good to share thing with other which helps other to understand the complexity behind this.I would like to thank mkyong for sharing his understanding with other and will be waiting for some more article to share by him. Once aging i would like to thank mkyong for such an nice article :-)
God bless you, mkyong.
Thank you, Mkyong! It’s very helpful for me with this sample :)
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 ?
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.
ya, this is one of the reason to create mkyong.com, i just want a working solution and full example.
Simple example, thanks! :)
Thanks a lot!
Excellent
Thanks a lot
You save my time. Thanks a lot.
thank you very much, it was extremely helpful.
Thanks Man!
i want this code but for general XML not spesific ??
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.
Obviously the xml get stripped out of the message, good going.
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
nice one
[...] 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 [...]
[...] Read XML file – (DOM Parser) Example to read a XML file with DOM parser. [...]
I d like to get a domme like this one ! More posts like this?
‘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
I can just say thank you for this wonderful post!
[...] 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) [...]
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
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**.
Both SAX and DOM has their target audience :)
Thanks for the tip man!