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.


<?xml version="1.0"?>
		<role>Java Developer</role>
		<role>CSS Developer</role>

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) { = 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;
    public String toString() {
        return "Employee:: 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.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);
            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++) {
            //lets print Employee list information
            for (Employee emp : empList) {
        } catch (SAXException | ParserConfigurationException | IOException e1) {


    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 Doc


  1. Jérôme Angibaud says:

    Hi Pankaj.

    There is a new innovative library to manipulate DOML/XML. Have a look at :

  2. 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();


  3. Anjan Bhattacharya says:

    I got error ” java.lang.ClassCastException: cannot be cast to javax.lang.model.element.Element
    can u provide me the solution?

  4. sagar says:

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

  5. 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.

  6. 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.

      1. pushpa says:

        Hi pankaj i run above program for my xml



        but for this i am getting error Exception in thread “main” java.lang.NullPointerException
        can u please help me

  7. HIMANSU NAYAK says:

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

  8. Dev says:

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

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors