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
org.jdom2.input.DOMBuilder
: Uses DOM Parser to parse the XML and transform it to JDOM Document.org.jdom2.input.SAXBuilder
: Uses SAX Parser to parse the XML and transform it to JDOM Document.org.jdom2.input.StAXEventBuilder
: Uses STAX Event Parser to parse the XML and transform it to JDOM Document.org.jdom2.input.StAXStreamBuilder
: Uses STAX Stream Parser to parse the XML and transform it to JDOM Document.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.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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
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.
1 2 3 4 5 |
<span style="color: #003300;"><strong><code> 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 </code></strong></span> |
We can use SAX and STAX Parser also, here are other useful methods that we can use to use them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
//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.