How to read XML File in Java (DOM Parser)

Filed Under: Java

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

how to read xml file in java, java dom parser, java parse xml file
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.

employee.xml


<?xml version="1.0"?>
<Employees>
	<Employee>
		<name>Pankaj</name>
		<age>29</age>
		<role>Java Developer</role>
		<gender>Male</gender>
	</Employee>
	<Employee>
		<name>Lisa</name>
		<age>35</age>
		<role>CSS Developer</role>
		<gender>Female</gender>
	</Employee>
</Employees>

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.


package com.journaldev.xml;

public class Employee {
    private String name;
    private String gender;
    private int age;
    private String role;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    
    @Override
    public String toString() {
        return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender +
                " Role=" + this.role;
    }
    
}

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.


package com.journaldev.xml;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class XMLReaderDOM {

    public static void main(String[] args) {
        String filePath = "employee.xml";
        File xmlFile = new File(filePath);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);
            doc.getDocumentElement().normalize();
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            NodeList nodeList = doc.getElementsByTagName("Employee");
            //now XML is loaded as Document in memory, lets convert it to Object List
            List<Employee> empList = new ArrayList<Employee>();
            for (int i = 0; i < nodeList.getLength(); i++) {
                empList.add(getEmployee(nodeList.item(i)));
            }
            //lets print Employee list information
            for (Employee emp : empList) {
                System.out.println(emp.toString());
            }
        } catch (SAXException | ParserConfigurationException | IOException e1) {
            e1.printStackTrace();
        }

    }


    private static Employee getEmployee(Node node) {
        //XMLReaderDOM domReader = new XMLReaderDOM();
        Employee emp = new Employee();
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            emp.setName(getTagValue("name", element));
            emp.setAge(Integer.parseInt(getTagValue("age", element)));
            emp.setGender(getTagValue("gender", element));
            emp.setRole(getTagValue("role", element));
        }

        return emp;
    }


    private static String getTagValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = (Node) nodeList.item(0);
        return node.getNodeValue();
    }

}

Output of the above program is:


Root element :Employees
Employee:: Name=Pankaj Age=29 Gender=Male Role=Java Developer
Employee:: Name=Lisa Age=35 Gender=Female Role=CSS Developer

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 W3.org Doc

Comments

  1. sai says:

    Hi Pankaj,

    NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
    Here why can’t use getTextContent(),instead of taking the value from node.
    String value = element.getElementsByTagName(tag).item(0).getTextContent();

    Thanks.

  2. Anjan Bhattacharya says:

    Hi,
    I got error ” java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredElementImpl cannot be cast to javax.lang.model.element.Element
    “.
    can u provide me the solution?

  3. sagar says:

    Nice program Pankaj…can u write one program to access multiple xml files.
    and search elements

  4. Julia says:

    Hello, I use this DOMParser but I read the XML from url. For some reason, I dont’t understand why, when I update the XML, the parser still reads the original xml. Can you please tell me what am I doing wrong?

    1. Mohammed Muntazim says:

      use DOMParser when your xml file is constant.if your xml file is changing frequently then read xml through JAVA code.

  5. Avinash Kumar says:

    Hi Pankaj,

    Can you please help me, as i run the above program it gives a java.ioFileNotFoundException and taking the path as C:UsersAviDocumentsNetBeansProjectsJavaCollectionsemployee.xml (The system cannot find the file specified)
    instead of
    C:UsersAviDocumentsNetBeansProjectsJavaCollectionssrcemployee.xml (The system cannot find the file specified)

    1. Pankaj says:

      you need to correct the build path, keep file in the project root directory.

  6. HIMANSU NAYAK says:

    Hi Pankaj,
    Can you please let me know what is the purpose of
    “doc.getDocumentElement().normalize();” in XMLReaderDOM.java file

  7. Dev says:

    Hello, I’m looking for an implementation of this kind of xml. Could you help?
    Sorry forgot the xml earlier

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages