JDOM
Read XML File in Java using JDOM parser example
In this example we are going to see how to parse an XML File using JDOM. JDOM is a Java representation of an XML. It’s a very easy to use tool and it has a straightforward API. It’s an alternative to DOM and SAX and it integrates equally well with both of them.
JDOM is an external library and you have to download it from the official JDOM page. After downloading the zip folder you have to add the jars to your CLASSPATH. If you’re using Maven with your project you have to declare the appropriate dependencies:
<dependency> <groupId>jdom</groupId> <artifactId>jdom</artifactId> <version>2.0.4</version> </dependency>
Here is the XML File we are going to use for this demonstration.
testFile.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><company> <employee id="10"> <firstname>Jeremy</firstname> <lastname>Harley</lastname> <email>james@example.org</email> <department>Human Resources</department> <salary>2000000</salary> <address>34 Stanley St.©</address> </employee> <employee id="2"> <firstname>John</firstname> <lastname>May</lastname> <email>john@example.org</email> <department>Logistics</department> <salary>400</salary> <address>123 Stanley St.</address> </employee> </company>
ReadXMLFileWithJDOM.java
package com.javacodegeeks.java.core; import java.io.File; import java.io.IOException; import java.util.List; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; public class ReadXMLFileWithJDOM { private static final String xmlFilePath="C:\\Users\\nikos7\\Desktop\\filesForExamples\\testFile.xml"; public static void main(String[] args) { SAXBuilder saxBuilder = new SAXBuilder(); File xmlFile = new File(xmlFilePath); try { Document document = (Document) saxBuilder.build(xmlFile); Element rootElement = document.getRootElement(); List listElement = rootElement.getChildren("employee"); for (int i = 0; i < listElement.size(); i++) { Element node = (Element) listElement.get(i); System.out.println("First Name : " + node.getChildText("firstname")); System.out.println("Last Name : " + node.getChildText("lastname")); System.out.println("Email : " + node.getChildText("email")); System.out.println("Department : " + node.getChildText("department")); System.out.println("Salary : " + node.getChildText("salary")); System.out.println("Address : " + node.getChildText("address")); } } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } } }
Output:
First Name : Jeremy
Last Name : Harley
Email : james@example.org
Department : Human Resources
Salary : 2000000
Address : 34 Stanley St.©
First Name : John
Last Name : May
Email : john@example.org
Department : Logistics
Salary : 400
Address : 123 Stanley St.
This was an example on how to read XML File in Java using JDOM parser.