Java XML Tutorial

How to read XML file in Java – (JDOM Parser)

JDOM is open-source Java-based XML parser framework built on top of DOM and SAX, also a document object model(DOM) in-memory representation of an XML document.

JDOM makes navigating XML documents easier by providing more straightforward APIs and a standard Java-based collection interface. If you don’t mind downloading a small library to parse an XML file, the JDOM APIs are straightforward to use.

Table of contents

P.S Tested with JDOM 2.0.6

1. Download the JDOM 2.x library

The JDOM is not part of the Java built-in APIs, and we need to download the JDOM library.

Maven for JDOM.

pom.xml

  <dependency>
      <groupId>org.jdom</groupId>
      <artifactId>jdom2</artifactId>
      <version>2.0.6</version>
  </dependency>

2. Read or Parse an XML file (JDOM)

This example shows how to use JDOM to parse an XML file.

2.1 An XML file.

src/main/resources/staff.xml

<?xml version="1.0" encoding="utf-8"?>
<Company>
    <staff id="1001">
        <name>mkyong</name>
        <role>support</role>
        <salary currency="USD">5000</salary>
        <!-- for special characters like < &, need CDATA -->
        <bio><![CDATA[HTML tag <code>testing</code>]]></bio>
    </staff>
    <staff id="1002">
        <name>yflow</name>
        <role>admin</role>
        <salary currency="EUR">8000</salary>
        <bio><![CDATA[a & b]]></bio>
    </staff>
</Company>

2.2 JDOM example of parsing and printing out all the XML elements and nodes.

ReadXmlJDomParser.java

package com.mkyong.xml.jdom;

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

import javax.xml.XMLConstants;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class ReadXmlJDomParser {

  private static final String FILENAME = "src/main/resources/staff.xml";

  public static void main(String[] args) {

      try {

          SAXBuilder sax = new SAXBuilder();

          // https://rules.sonarsource.com/java/RSPEC-2755
          // prevent xxe
          sax.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
          sax.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

          // XML is a local file
          Document doc = sax.build(new File(FILENAME));

          Element rootNode = doc.getRootElement();
          List<Element> list = rootNode.getChildren("staff");

          for (Element target : list) {

              String id = target.getAttributeValue("id");
              String name = target.getChildText("name");
              String role = target.getChildText("role");
              String salary = target.getChildText("salary");
              String currency = "";
              if (salary != null && salary.length() > 1) {
                  // access attribute
                  currency = target.getChild("salary").getAttributeValue("currency");
              }
              String bio = target.getChildText("bio");

              System.out.printf("Staff id : %s%n", id);
              System.out.printf("Name : %s%n", name);
              System.out.printf("Role : %s%n", role);
              System.out.printf("Salary [Currency] : %,.2f [%s]%n", Float.parseFloat(salary), currency);
              System.out.printf("Bio : %s%n%n", bio);

          }

      } catch (IOException | JDOMException e) {
          e.printStackTrace();
      }

  }
}

Output

Terminal

Staff id : 1001
Name : mkyong
Role : support
Salary [Currency] : 5,000.00 [USD]
Bio : HTML tag <code>testing</code>

Staff id : 1002
Name : yflow
Role : admin
Salary [Currency] : 8,000.00 [EUR]
Bio : a & b

3. Read or Parse a remote XML file (JDOM)

This example uses a JDOM parser to read or parse a remote or website-based XML file.

3.1 Visit the Alexa API https://data.alexa.com/data?cli=10&url=mkyong.com, and it will return the below XML file.


<ALEXA VER="0.9" URL="mkyong.com/" HOME="0" AID="=" IDN="mkyong.com/">
  <SD>
    <POPULARITY URL="mkyong.com/" TEXT="20152" SOURCE="panel"/>
    <REACH RANK="14434"/>
    <RANK DELTA="+728"/>
    <COUNTRY CODE="IN" NAME="India" RANK="5322"/>
  </SD>
</ALEXA>

3.2 JDOM example of getting the website’s Alexa rank.

ReadXmlAlexaApiJDomParser.java

package com.mkyong.xml.jdom;

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

import javax.xml.XMLConstants;
import java.io.IOException;
import java.net.URL;
import java.util.List;

public class ReadXmlAlexaApiJDomParser {

    private static final String REMOTE_URL
        = "https://data.alexa.com/data?cli=10&url=mkyong.com";

    public static void main(String[] args) {

        try {

            SAXBuilder sax = new SAXBuilder();

            // https://rules.sonarsource.com/java/RSPEC-2755
            // prevent xxe
            sax.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
            sax.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

            // XML is in a web-based location
            Document doc = sax.build(new URL(REMOTE_URL));

            Element rootNode = doc.getRootElement();
            List<Element> list = rootNode.getChildren("SD");

            for (Element target : list) {

                Element popularity = target.getChild("POPULARITY");

                String url = popularity.getAttributeValue("URL");
                String rank = popularity.getAttributeValue("TEXT");

                System.out.printf("URL : %s%n", url);
                System.out.printf("Alexa Rank : %s%n", rank);

            }

        } catch (IOException | JDOMException e) {
            e.printStackTrace();
        }

    }
}

Output

Terminal

URL : mkyong.com/
Alexa Rank : 20152

4. String that contains XML

This example shows how JDOM parses a String that contains XML.

ReadXmlStringJDomParser.java

package com.mkyong.xml.jdom;

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

import java.io.IOException;
import java.io.StringReader;

public class ReadXmlStringJDomParser {

    public static void main(String[] args) {

        String XML = "<root><url>mkyong</url></root>";

        try {

            SAXBuilder sax = new SAXBuilder();
            // String that contains XML
            Document doc = sax.build(new StringReader(XML));

            Element rootNode = doc.getRootElement();
            System.out.println(rootNode.getChildText("url"));

        } catch (IOException | JDOMException e) {
            e.printStackTrace();
        }

    }
}

Output

Terminal

mkyong

Note
More JDOM2 examples – JDOM2 A Primer

5. Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-xml

$ cd src/main/java/com/mkyong/xml/jdom/

6. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
SomeGuy
8 years ago

you can see all the children with a for
for (Element child: rootNode.getChildren()){
println child.getText() //or you can use child.content
}

south korean java develper
10 months ago

very nice!!
thank’s a lot~~~
god bless you!

Mahdi
1 year ago

Hello

When I use : Documen doc = sax.build(new File((FILENAME)); , JDOMException run and try loop don’t run. I searched, but I couldn’t resolve that.
I hope you resolve my problem.

Thank’s a lot

ismaeel shokoohi
2 years ago

Hello

How can I read nested tags?

example :

<people>
  <person>
    <xxx>
         <b>bbb</b>
         <c>ccc</c>
         <d>ddd</d>
   </xxx>
  </person>
</people>

now how read tag<b> ???

Thankyou