JDOM Parser – Read XML file to Object in Java

Filed Under: Java

JDOM parser provides us a great Java XML API to read, edit and write XML documents easily. JDOM provides wrapper classes to chose your underlying implementation from SAX Parser, DOM Parser, STAX Event Parser and STAX Stream Parser.

JDOM Parser

In this tutorial, we will learn how to read XML file to Object using JDOM Parser.

JDOM is not part of standard JDK, so to work with JDOM you will need to download it’s 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 tutorial, I am using current JDOM version 2.0.4 (jdom-2.0.4.jar).

As I said earlier, JDOM provides wrapper classes to chose your preferred XML API, it comes with four important classes using which we can get JDOM Document Object. JDOM Document object provides useful methods to get the root element, list of child elements, getting attribute value for an element and getting element value from name.

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.

JDOM Example

Let’s start with our sample program to read XML to Object using JDOM Parser.

employees.xml


<?xml version="1.0" encoding="UTF-8"?>
<Employees>
	<Employee id="1">
		<age>29</age>
		<name>Pankaj</name>
		<gender>Male</gender>
		<role>Java Developer</role>
	</Employee>
	<Employee id="2">
		<age>35</age>
		<name>Lisa</name>
		<gender>Female</gender>
		<role>CEO</role>
	</Employee>
	<Employee id="3">
		<age>40</age>
		<name>Tom</name>
		<gender>Male</gender>
		<role>Manager</role>
	</Employee>
</Employees>

Employee object to represent the Employee element in the XML.


package com.journaldev.xml;

public class Employee {
    private int id;
    private String name;
    private String gender;
    private int age;
    private String role;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    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:: ID="+this.id+" Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender +
                " Role=" + this.role;
    }
    
}

Here is the test program using DOMBuilder to read the XML file to list of Employee object.


package com.journaldev.xml.jdom;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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 javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.DOMBuilder;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.StAXEventBuilder;
import org.jdom2.input.StAXStreamBuilder;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.journaldev.xml.Employee;


public class JDOMXMLReader {

    public static void main(String[] args) {
        final String fileName = "/Users/pankaj/employees.xml";
        org.jdom2.Document jdomDoc;
        try {
            //we can create JDOM Document from DOM, SAX and STAX Parser Builder classes
            jdomDoc = useDOMParser(fileName);
            Element root = jdomDoc.getRootElement();
            List<Element> empListElements = root.getChildren("Employee");
            List<Employee> empList = new ArrayList<>();
            for (Element empElement : empListElements) {
                Employee emp = new Employee();
                emp.setId(Integer.parseInt(empElement.getAttributeValue("id")));
                emp.setAge(Integer.parseInt(empElement.getChildText("age")));
                emp.setName(empElement.getChildText("name"));
                emp.setRole(empElement.getChildText("role"));
                emp.setGender(empElement.getChildText("gender"));
                empList.add(emp);
            }
            //lets print Employees list information
            for (Employee emp : empList)
                System.out.println(emp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //Get JDOM document from DOM Parser
    private static org.jdom2.Document useDOMParser(String fileName)
            throws ParserConfigurationException, SAXException, IOException {
        //creating DOM Document
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new File(fileName));
        DOMBuilder domBuilder = new DOMBuilder();
        return domBuilder.build(doc);

    }
}

As you can see that I am using DOM parser wrapper class to get the JDOM Document object.

When I run above program, here is the output.


Employee:: ID=1 Name=Pankaj Age=29 Gender=Male Role=Java Developer
Employee:: ID=2 Name=Lisa Age=35 Gender=Female Role=CEO
Employee:: ID=3 Name=Tom Age=40 Gender=Male Role=Manager

We can use SAX and STAX Parser also, here are other useful methods that we can use to use them.


    //Get JDOM document from SAX Parser
    private static org.jdom2.Document useSAXParser(String fileName) throws JDOMException,
            IOException {
        SAXBuilder saxBuilder = new SAXBuilder();
        return saxBuilder.build(new File(fileName));
    }
    
    //Get JDOM Document from STAX Stream Parser or STAX Event Parser
    private static org.jdom2.Document useSTAXParser(String fileName, String type) throws FileNotFoundException, XMLStreamException, JDOMException{
        if(type.equalsIgnoreCase("stream")){
            StAXStreamBuilder staxBuilder = new StAXStreamBuilder();
            XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
            XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new FileInputStream(fileName));
            return staxBuilder.build(xmlStreamReader);
        }
        StAXEventBuilder staxBuilder = new StAXEventBuilder();
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileInputStream(fileName));
        return staxBuilder.build(xmlEventReader);
        
    }

You will get the same output with above methods also because they are just changing the parser and finally returning the same Document.

Benefit of using JDOM is that you can switch from SAX to DOM to STAX Parser easily, you can provide factory methods to let client application chose the implementation.

You might want to head over to any of these.

Comments

  1. deepali says:

    hello…please tell me what settigs do i need to perform in netbeans IDE 8.1 to invoke this parser.

  2. Abhi says:

    Really nice explanation, Thanks a lot.

  3. Anil says:

    Cool demo, as always.

  4. matthieu526 says:

    Thank you very much for this wonderful explanation ! It is helping me a lot 🙂

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