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

JDOM is, quite simply, a Java representation of an XML document. JDOM provides a way to represent that document for easy and efficient reading, manipulation, and writing. It has a straightforward API, is a lightweight and fast, and is optimized for the Java programmer. It’s an alternative to DOM and SAX, although it integrates well with both DOM and SAX.

JDOM, Java XML parser, is more user friendly in the way of accessing the XML document.

In this example, we show you how to use JDOM to read a XML file, and print out each element orderly.

1. Download the JDOM library

JDOM is not like SAX or DOM, which bundled in JDK. To use JDOM, you need to download the library manually.

Get JDOM from JDOM official site or declares following dependency if you are using Maven.


    <dependency>
	<groupId>jdom</groupId>
	<artifactId>jdom</artifactId>
	<version>1.1</version>
    </dependency>

2. XML File

XML file as following


<?xml version="1.0"?>
<company>
	<staff>
		<firstname>yong</firstname>
		<lastname>mook kim</lastname>
		<nickname>mkyong</nickname>
		<salary>100000</salary>
	</staff>
	<staff>
		<firstname>low</firstname>
		<lastname>yin fong</lastname>
		<nickname>fong fong</nickname>
		<salary>200000</salary>
	</staff>
</company>

3. Java File

Use JDOM parser to parse above XML file.


import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class ReadXMLFile {
	public static void main(String[] args) {

	  SAXBuilder builder = new SAXBuilder();
	  File xmlFile = new File("c:\\file.xml");

	  try {

		Document document = (Document) builder.build(xmlFile);
		Element rootNode = document.getRootElement();
		List list = rootNode.getChildren("staff");

		for (int i = 0; i < list.size(); i++) {

		   Element node = (Element) list.get(i);

		   System.out.println("First Name : " + node.getChildText("firstname"));
		   System.out.println("Last Name : " + node.getChildText("lastname"));
		   System.out.println("Nick Name : " + node.getChildText("nickname"));
		   System.out.println("Salary : " + node.getChildText("salary"));

		}

	  } catch (IOException io) {
		System.out.println(io.getMessage());
	  } catch (JDOMException jdomex) {
		System.out.println(jdomex.getMessage());
	  }
	}
}

Output


First Name : yong
Last Name : mook kim
Nick Name : mkyong
Salary : 100000
First Name : low
Last Name : yin fong
Nick Name : fong fong
Salary : 200000

About the Author

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

Comments

avatar
22 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
18 Comment authors
mist42nzNaresh DhondiSomeGuyJAHMKJoe Recent comment authors
newest oldest most voted
mist42nz
Guest
mist42nz

Found this really didn’t work, as various parts were Contents and not elements and vice versa

Naresh Dhondi
Guest
Naresh Dhondi

It’s very simple solution for Reading xml thanks…but my reuirement is i need read xsd (i dont have a prolog as , )format xml file ,I have just like so how should i read xml data from this type prolog file. please help me….

JAHMK
Guest
JAHMK

Very Simple!! saved lot of time.
thanks…. :D

Joe
Guest
Joe

On the line – Element rootNode = document.getRootElement();

I get the error – Cannot resolve method ‘getRootElement();’

Gustavo Stork
Guest
Gustavo Stork

What I need to do for read more elements in the tree? For example : Everyday Italian “children of author” Frida “children of author”Deserto “children of author”Guia “children of author”Origem 2005 30.00 because the “for” just get a first element in the node. someone help me please.

SomeGuy
Guest
SomeGuy

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

Oleksa
Guest
Oleksa

best tutorials ever

clemon
Guest
clemon

Please note that if you’re using JDOM version 2.0.5, you’ll have to include a ‘2’ in the following imports:

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

Goutham
Guest
Goutham

is JDOM for marshalling/unmarshalling.???
or just for reading from xml and creating an xml.???
what is the major differences and similorities between both..???

arthur
Guest
arthur

Thanks for the great post! Top notch and strait to the point, as always! Love you guys!

But notice that there is version 2.0 for maven available, with org.jdom as groupId:

org.jdom
jdom
2.0.0

Neha
Guest
Neha

Hi,

I want to read multiple xml files dynamically. Can you please suggest me how to do this??

Thanks

Rui Martins
Guest
Rui Martins

I’m trying to use Jdom to read a xml file.
This is thecontent of the file. I’m trying to read all the elements, but no success so far. How do I do it?

200
Success
Notes details fetched successfully.

isPublic
false

notesText
dfgfdgdfgdfgdgdgdgdgdg

userName
Howard Stern

notesDate
1373971580200

isPublic
false

notesText
dfgdfgdfgdfgdfgdfgdfgdf

userName
Howard Stern

notesDate
1373967102396

isPublic
true

notesText
dfgdfgdfgdfgdfgdfgdgdgdgd

userName
Howard Stern

notesDate
1373967097117

jayaram
Guest
jayaram

Simply Superb !!

But Nice to provide some more info,like how to read CDATA elements and how read xml from end of file.

Thanx

Boris Monson
Guest
Boris Monson

Great.Thanks for post.I saved my time.

Bao
Guest
Bao

Very nice, clear and easy to understand, thanks

Luca Zammataro
Guest
Luca Zammataro

magic! thank you!

MinhKhai
Guest
MinhKhai

can you show me how to display sfaffs which have salary between A and B. thanks very much

Pankaj
Guest
Pankaj

JDOM provides wrapper around common Parsers like DOM, SAX and STAX. We can use any of these to parse XML to Object.

Please have a look http://www.journaldev.com/1206/jdom-parser-read-xml-file-to-object-in-java

trackback
Java XML Tutorial

[…] for easy and efficient reading, manipulation, and writing. It’s an alternative to DOM and SAX.Read a XML file Read a XML file and print it out each elements.Modify existing XML file Modify an existing XML […]

trackback
Long day, with Happy End « CodeFever

[…] It’s really easy for newbies. If somebody want to know how it works, contact me or read the jdom-example/ . Now a little pic of my little […]

trackback
android ?????? | ????

[…] ?DOM??xml?? […]

trackback
android ?????? | ????

[…] ?DOM??xml?? […]

Lindsay Pieffer
Guest
Lindsay Pieffer

Sweet Post!