How to read XML file in Java

This tutorial shows how to read and parse an XML file in Java using a DOM parser.

1- Define XML file

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 afterward are done on the Document object.

3- Read the root node

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

In students.xml, the root node is students.

4- Retrieve nodes by tag name

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.

The ELEMENT_NODE type refers to a non-text node that has 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 the students.xml file and print out the text elements.

Running the above method would give the following output:

5- Get Node by 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 a 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- Resources

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

5 1 vote
Article Rating

Hussein Terek

Owner of programmergate.com, I have a passion for software engineering and everything related to Java environment.

guest
0 Comments
Inline Feedbacks
View all comments