How to read XML File in Java (DOM Parser) With Examples

Today we will learn how to read the XML file in Java. We will also learn how to parse an XML file in java to object using DOM parser.

DOM XML Parser is easiest to understand. It loads the XML object into memory as Document, then you can easily traverse different elements and nodes in the object. The traversing of elements and nodes are not required to be in order.

How to read XML File in Java

DOM Parser are good for small XML documents but since it loads complete XML file into memory, it’s not good for large XML files. For large XML files, you should use SAX Parser.

In this tutorial, we will read the XML file and parse it to create an object from it.

Here is the XML file that will be read in this program.


So this XML is the list of employees, to read this XML file I will create a bean object Employee and then we will parse the XML to get the list of employees.

Here is the Employee bean object.

Notice that I have overridden toString() method to print useful information about the employee.

Read this post to know you should always use @Override annotation to override methods.

If you are new to annotations, read java annotations tutorial.

Java DOM Parser

Here is the java program that uses DOM Parser to read and parse XML file to get the list of Employee object.

Output of the above program is:

In real life, it’s not a bad idea to validate XML file before parsing it to objects, learn how to validate XML against XSD in java. That’s all about how to read xml file or parse xml file in java.

Reference: Official Doc

By admin

Leave a Reply

%d bloggers like this: