How to Read XML File in Java- JDOM Parser

In this article, we will discuss how to read XML file in Java using JDOM parser.
JDOM is an open source, Java-based library to parse XML documents. It is typically a Java developer-friendly API. It is Java optimized and it uses Java collections like List and Arrays.
JDOM works with DOM and SAX APIs and combines the best of the two. It is of low memory footprint and is nearly as fast as SAX.

JDOM Dependency

JDOM is not part of standard JDK, so to work with JDOM you will need to download its binaries from JDOM Official Website. Once binaries are downloaded, include JDOM jar in your project classpath and you are good to start using it. For this example, we will use current JDOM version 2.0.6 (jdom-2.0.6.jar). If you are working with a maven based project then add below maven dependency to your pom.xml.
<!-- https://mvnrepository.com/artifact/org.jdom/jdom2 -->
<dependency>
 <groupId>org.jdom</groupId>
 <artifactId>jdom2</artifactId>
 <version>2.0.6</version>
</dependency>

JDOM Parser Important Classes

  1. org.jdom2.input.DOMBuilder: Uses DOM Parser to parse the XML and transform it to JDOM Document.
  2. org.jdom2.input.SAXBuilder: Uses SAX Parser to parse the XML and transform it to JDOM Document.
  3. org.jdom2.input.StAXEventBuilder: Uses STAX Event Parser to parse the XML and transform it to JDOM Document.
  4. org.jdom2.input.StAXStreamBuilder: Uses STAX Stream Parser to parse the XML and transform it to JDOM Document.
  5. org.jdom2.Document: JDOM Document provides useful methods to get root element, read, edit and write content to Elements. Here we will use it to get the root element from XML.
  6. org.jdom2.Element: Provides useful methods to get list of child elements, get child element value, get attribute values.
Read more about JDOM on JDOM Tutorial

Program Development Steps

  1. Input jdom_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 JDOM Parser

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

Make sure that you have a jdom_users.xml file in a file system and add the below contents to this file:
<?xml version="1.0" encoding="UTF-8"?>
<Users>
 <User id= "1">
  <firstName>Ramesh</firstName>
  <lastName>Fadatare</lastName>
  <age>28</age>
  <gender>Male</gender>
 </User>
 <User id= "2">
  <firstName>John</firstName>
  <lastName>Cena</lastName>
  <age>45</age>
  <gender>Male</gender>
 </User>
 <User id= "3">
  <firstName>Tom</firstName>
  <lastName>Cruise</lastName>
  <age>40</age>
  <gender>Male</gender>
 </User>
</Users>

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

User object to represent the User element in the XML.
package net.javaguides.javaxmlparser.jdom;

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 JDOM Parser

Here is the test program using DOMBuilder to read the XML file to list of User object.
package net.javaguides.javaxmlparser.jdom;

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

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class ReadXMLFile {
    public static void main(String[] args) {
        final String fileName = "jdom_users.xml";
        try {
            // we can create JDOM Document from DOM, SAX and STAX Parser Builder classes
            SAXBuilder builder = new SAXBuilder();
            File xmlFile = new File(fileName);
            Document jdomDoc = (Document) builder.build(xmlFile);
            Element root = jdomDoc.getRootElement();
            List < Element > listOfUsers = root.getChildren("User");
            List < User > userList = new ArrayList < > ();

            for (Element userElement: listOfUsers) {
                User user = new User();
                user.setId(Integer.parseInt(userElement.getAttributeValue("id")));
                user.setAge(Integer.parseInt(userElement.getChildText("age")));
                user.setFirstName(userElement.getChildText("firstName"));
                user.setLastName(userElement.getChildText("lastName"));
                user.setGender(userElement.getChildText("gender"));
                userList.add(user);
            }
            // lets print Users list information
            userList.forEach(user - > {
                System.out.println(user.toString());
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
Ouput of above program is:
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]

Comments