JDOM Parser - Read XML file to Object in Java With Examples

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

Employee object to represent the Employee element in the XML.

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

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.

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

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.

By admin

Leave a Reply

%d bloggers like this: