Read XML in Java using JDom Parser

JDom is an open source library for manipulating XML documents. It has an easier API then the standard Java JDK libraries. In the following tutorial we explain how you can read an XML file in Java using the JDom Parser.

JDom Maven Dependency

Because JDom is not part of the standard JDK, you’ll have to download the binaries from there website or if you use Maven, you can add the following dependency.


Read XML File

In this example we are going to read the following example.xml file. As you can see, it contains a root element courses, which contains a list of course elements. The course element contains an attribute and other elements. Note that in the last element we included a CDATA element to encapsulate special characters.

<?xml version="1.0" encoding="UTF-8"?>
    <course id="1">
        <name>Read XML Document using JDom Parser</name>
    <course id="2">
        <name>Getting Started with JDom</name>
    <course id="3">
               reading characters with special markup (& ? $ ^ < >)

First, we read the example.xml file via an InputStream. Then we create a SAXBuilder which builds the XML document based on that InputStream. After the build() method successfully completes, the XML document is loaded into memory and ready for processing. Finally, we iterate over the XML elements and simply print the values to the console.

package com.memorynotfound.xml.jdom;

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

import java.util.List;

public class ReadXmlJDom {

    public static void main(String... args) throws JDOMException, IOException {

        // read file from classpath
        InputStream in = ReadXmlJDom.class.getResourceAsStream("/example.xml");

        // create builder
        SAXBuilder builder = new SAXBuilder();

        // parse and load file into memory
        Document document =;

        // getting the root element
        Element root = document.getRootElement();
        System.out.println("Root: " + root.getName());
        System.out.println("- - - - - - - - - - - - - - - - - - -");

        // iterating over the children
        List<Element> courses = root.getChildren("course");
        for (Element element : courses){
            System.out.println("\nElement: " + element.getName());
            System.out.println("ID: " + element.getAttributeValue("id"));
            System.out.println("Name: " + element.getChildText("name").trim());
            System.out.println("Price: " + element.getChildText("price"));

The previous code, generates the following output:

Root: courses
- - - - - - - - - - - - - - - - - - -

Element: course
ID: 1
Name: Read XML Document using JDom Parser
Price: 0.0

Element: course
ID: 2
Name: Getting Started with JDom
Price: 0.0

Element: course
ID: 3
Name: reading characters with special markup (& ? $ ^ < >)
Price: 12.0



You may also like...