How to read XML file in Java

In this tutorial, we show how to read and parse an XML file using DOM parser provided by JDK.

If you’re interested in SAX or STAX parser, please refer to these tutorials: SAX parser, STAX parser.

1- Students.xml

Consider we have the following Students.xml file:

2- Instantiate XML file

DOM parser loads the whole XML document into the memory and considers every XML tag as an element.

In order to instantiate a new Document object from an XML file, we do the following:

This is done only once and all the parsing operations afterwards are done on Document object.

3- Get Root Node

To get the root node or element of an XML file, use the following:

In students.xml, the root node is: students.

4- Get All Nodes

To retrieve all nodes of a specific tag name, use getElementsByTagName() method.

In the following example, we parse students.xml and print out all the defined students.

where ELEMENT_NODE type refers to a non-text node which have sub-elements.

Calling the above method would give the following output:

In order to parse the whole XML file starting from the root node, you can recursively call getChildNodes() method as the following:

In this example, we parse students.xml file and print out the text elements.

Running the above method would give the following output:

5- Get Node by text value

In order to search for a node by its value, you can use getElementsByTagName() method and check on the value of its text element.

In this example, we are looking for the student who has a specific id.

Now, if we call the method as:

we get the following output:

6- Get Node by attribute value

In order to search for a node by the value of a specific attribute, you can use getElementsByTagName() along with getAttribute() methods as the following:

In this example, we are looking for all graduated students i.e. students who have (graduated=”yes”) attribute.

Now, if we call the method as:

We get the following output:

7- Source Code

You can download the source code from this repository: Read-XML

P.S: refer to How to create XML file in Java in order to check how to create a new XML file programatically using DOM parser.

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar