Read XML file using DOM

The DOM is a collection of interfaces that make it easy to access and modify the structure and content of an XML file. In this article, we will learn how to read XML files using your DOM!

DOM interfaces

The DOM defines several Java interfaces, below are some of the interfaces that we often use when working with it:

  • Document
  • Node
  • Element
  • Attr
  • Text

I will explain each of these interfaces when we go into a specific example.

For example, reading XML files using DOM

In order for you to imagine, I will create and work with a Maven project to illustrate this article.

I have the following project:

dom-parser-1

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

This file contains information for 2 students including name ( name ), student code ( code ) and age ( age ) of each student. Each student will be numbered through the n0 attribute .

OK, let's start reading this file!

First, 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 File object created above

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

In students.xml file, the student tag is the most outer tag, or root element. To read this tag we use the following method:

In the DOM, a tag is defined as an Element.

Now that we have student card information, to get student card information, we will use student cards to get them.

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

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

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

To read the sequence number attribute, we just need to do the following:

with n0 is the name of the attribute.

Because we are currently reading the student card and each student card has only one child card for name, student code and age, we can read this information as follows:

Name tags:

Student code card:

Age card:

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

Techtalk talk via huongdanjava

Share the news now