Reading XML using DOM parser in java

Dsforgood
2 min readFeb 10, 2022

In this article we will go through the process of reading a XML file using DOM parser in java. We will explain this with a full example. DOM stands for Document object model. The DOM API provides the classes to read and write an XML file. We can create, delete, modify, and rearrange the XML node using the DOM API. We have already done an article on SAX API which can only be used to reading XML.

DOM parser — How it works?

DOM parser parses the entire XML file and creates a DOM object in the memory. It models an XML file in a tree structure for easy traversal and manipulation. The DOM parser consumes memory whereas SAX do not.

DOM parser example

Now let us go through a coding example to understand the DOM API. We are using java 17 for development. First thing we need is a XML file. Below is the XML file for our example.

In the above XML file customers is the root tag. By the end of this example we will create a list of customers and then print its values. Next thing we need to do is to add the module dependency java.xml to our module descriptor.

We need a class to hold the customers. Below is that class.

Now is the main part of our example. Below is the complete code for DOM parser.

We can divide this process in tomultiple steps.

1, create file object for the XML file. Also declare ArrayList to hold our list.

2, create DocumentBuilderFactory instance.

3, create new DocumentBuilder

4, create Document object by using parse method.

5, get all customer nodes and then iterate through it. Extract the values of each node. Add the customer object to the Arraylist.

6, print the customer ArrayList.

Below is the output of this program.

Thank you for reading this article. If you are interested in learning java 17 I have a complete course for you please click here -> https://www.udemy.com/course/java-17-complete-course/?referralCode=C1A5CE9D4178AB159247

--

--

Dsforgood

We are a bunch of data science enthusiasts simplifying concepts and ideas in technology for common readers. We believe in using data science for good!