Read XML file using DOM in Java

The Document Object Model (DOM) is a collection of Java interfaces that makes us easy to access and modify the structure and content of an XML file. In this tutorial, we will learn how to read XML file using DOM in Java.

First, I’ll list some of the interfaces which we use when working with DOM:

  • org.w3c.dom.Document
  • org.w3c.dom.Node
  • org.w3c.dom.Element
  • org.w3c.dom.Attr
  • org.w3c.dom.Text

Each of these interfaces will have one or more classes implementing it, depending on the structure of the XML content we need to process.

Next, I will create and work with a Maven project to illustrate reading XML file using the DOM.

I have the following project:

Read XML file using DOM in Java

The XML file we need to read is students.xml with the following contents:

This file contains information about two students, including the name, code and age of each student. Each student will be numbered through the attribute n0.

OK, now we start reading this file!

First, to be able to read the students.xml file, we need to initialize the File object for this file:

Next, we need to initialize the Document object containing the information of the XML file from the generated File object:

To read the XML file with DOM, we will read each of its tags from outside into inside follow their hierarchical order.

In the students.xml file, the <students> tag is the outermost tag, also known as the root element. To read this tag we use the following method:

In DOM, a tag is defined as an element.

Now, we have the <students> tag information, to get the <student> tags information, we will use the <students> tag to retrieve them.

The NodeList object will contain the two <student> tag information contained in the XML file. Now we will go through each tag to read their information:

A Node is a node in our DOM tree. We need to convert it to the Element object to use.

OK, now we have the object containing the <student> tag information. The task now is to read them.

To read the “n0” attribute, we simply do the following:

where n0 is the name of the attribute.

Because now we are reading the <student> tag and every <student> tag has only one child tag for the student’s name, student code and age so we can read this information as follows:

  • <name> tag:

  • <code> tag:

  • <age> tag:

OK, we have finished reading the file students.xml, you can refer to full code as follows:

Result:

Read XML file using DOM in Java

Add Comment