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
- 1. Download the JDOM 2.x library
- 2. Read or Parse an XML file (JDOM)
- 3. Read or Parse a remote XML file (JDOM)
- 4. String that contains XML
- 5. Download Source Code
- 6. References
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.
<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.
<?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.
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
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.
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
URL : mkyong.com/
Alexa Rank : 20152
4. String that contains XML
This example shows how JDOM parses a String
that contains XML.
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
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
- JDOM website
- JDOM2 documentation
- Wikipedia – JDOM
- Wikipedia – Java API for XML Processing
- Oracle – Java API for XML Processing (JAXP)
- How to read XML file in Java – (DOM Parser)
- How to read XML file in Java – (SAX Parser)
- JAXB hello world example
- How to prevent XML external entity attack (XXE attack)
you can see all the children with a for
for (Element child: rootNode.getChildren()){
println child.getText() //or you can use child.content
}
very nice!!
thank’s a lot~~~
god bless you!
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
Hello
How can I read nested tags?
example :
now how read tag<b> ???
Thankyou