How to read XML file in Java - DOM Parser

In the previous articles, we have learned How to Modify XML File in Java using DOM Parser and How to Create XML File in Java using DOM Parser. In this article, we will learn how to read XML file in Java. We will also learn how to parse XML file to Java object using DOM XML Parser. DOM XML parser parses the entire XML document and loads it into memory; then models it in a “TREE” structure for easy traversal or manipulation.

In short, it turns an XML file into DOM or Tree structure, and we have to traverse a node by node to get what you want.
Warning: DOM Parser is slow and consumes a lot of memory when it loads an XML document which contains a lot of data. Please consider SAX parser as a solution for it, SAX is faster than DOM and use less memory.

Development Process Steps

  1. Input users.xml File(XML file we will read)
  2. Create User class (populate XML data into User object)
  3. Program to Read XML File in Java using Java DOM Parser

1. Input users.xml File(XML file we will read)

Here is the XML file that will be read in this program.
<?xml version="1.0" encoding="UTF-8"?>
<Users>
    <User>
        <id>1</id>
        <firstName>Ramesh</firstName>
        <lastName>Fadatare</lastName>
        <age>28</age>
        <gender>Male</gender>
    </User>
    <User>
        <id>2</id>
        <firstName>John</firstName>
        <lastName>Cena</lastName>
        <age>45</age>
        <gender>Male</gender>
    </User>
    <User>
        <id>3</id>
        <firstName>Tom</firstName>
        <lastName>Cruise</lastName>
        <age>40</age>
        <gender>Male</gender>
     </User>
</Users>

2. Create User class (populate XML data into User object)

So this XML is the list of users, to read this XML file we will create a bean object User and then we will parse the XML to get the list of users.
Here is the User bean object.
package net.javaguides.javaxmlparser.dom;

public class User {
    private int id;
    private String firstName;
    private String lastName;
    private int age;
    private String gender;

    public int getId() {
        return id;
    }

    public void setId(int i) {
        this.id = i;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", gender=" +
            gender + "]";
    }
}

3. Program to Read XML File in Java using Java DOM Parser

Here is the java program that uses DOM Parser to read and parse XML file to get the list of User object.
package net.javaguides.javaxmlparser.dom;

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;

/**
 * Java DOM Parser to Read XML File in Java 
 * @author Ramesh Fadatare
 *
 */

public class ReadXMLFileInJava {
    public static void main(String[] args) {
        String filePath = "users.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("User");
            // now XML is loaded as Document in memory, lets convert it to Object List
            List < User > userList = new ArrayList < User > ();

            for (int i = 0; i < nodeList.getLength(); i++) {
                userList.add(getUser(nodeList.item(i)));
            }
            // lets print User list information
            for (User emp: userList) {
                System.out.println(emp.toString());
            }
        } catch (SAXException | ParserConfigurationException | IOException e1) {
            e1.printStackTrace();
        }

    }

    private static User getUser(Node node) {
        // XMLReaderDOM domReader = new XMLReaderDOM();
        User user = new User();
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            user.setId(Integer.parseInt(getTagValue("id", element)));
            user.setFirstName(getTagValue("firstName", element));
            user.setLastName(getTagValue("lastName", element));
            user.setGender(getTagValue("gender", element));
            user.setAge(Integer.parseInt(getTagValue("age", element)));
        }
        return user;
    }

    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();
    }

}
The output of the above program:
Root element :Users
User [id=1, firstName=Ramesh, lastName=Fadatare, age=28, gender=Male]
User [id=2, firstName=John, lastName=Cena, age=45, gender=Male]
User [id=3, firstName=Tom, lastName=Cruise, age=40, gender=Male]
That’s all about how to read XML file or parse XML file in java.

Reference

Comments