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.
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(); } }
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.
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?
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!