Java-XML in 3 minutes

XML is a clear and concise way to describe data.

Let’s see an example:

<?xml version="1.0" encoding="UTF-8"?>
<message id="123">
    <text>Hello from XML!</text> 

This simple document represents a “message”.


The message has an attribute called @id.

<message id="...">

It has also three children.

<from> ... </from>
<to> ... </to>
<text> ... </text>

Step 1. Download dom4j

To download dom4j go to → Download → Download the current release SourceForge → dom4j-1.6.1.jar


If you are using Java 1.5 download dom4j-1.5.2.jar, and
If you are using Java 1.4 download; it has a dom4j-full.jar inside.

Step 2. Place the jar in the classpath

In Eclipse: Project → Java Build Path → Libraries → Add External JARs…

In Netbeans: File → “Project” Properties → Libraries → Add JAR/Folder

In JDeveloper 11g: Tools → Project Properties… → Libraries and Classpath → Add JAR/Directory…

Step 3. Create the XML document

	// Create the document
	Document document = DocumentHelper.createDocument();
	// Add the root
	Element root = document.addElement("message").addAttribute("id", "123");
	// Add the "from" element
	// Add the "to" element
	// Add the "text" element
	root.addElement("text").addText("Hello from XML!");

That’s all!

Step 4. Save the XML document

// Make a pretty output
		OutputFormat format = OutputFormat.createPrettyPrint();
// Save it
		XMLWriter writer = new XMLWriter(new FileWriter("C:/message.xml"), format);

Step 5. Read the XML document

// Locate the file
URL url = new File("C:/message.xml").toURI().toURL();
// Parse the document
Document document = new SAXReader().read(url);

Step 6. Get the information

// Get the root element
Element root = document.getRootElement();
// Get the id attribute
// Get the from element
Element from = root.element("from");
if (from != null) {

Step 7. Use some XPATH

// Get the root element
Element root = document.getRootElement();
// Get the id attribute
// Get the from element
Node from = root.selectSingleNode("./from");
if (from != null) {

A good XML tutorial can be found at

Thank you.


3 Responses to Java-XML in 3 minutes

  1. Dimitris says:

    Bravo Nikolae, this a good chance for all the junior developers to get familiars with programming.
    Keep walking 🙂
    We are with your side

  2. jimmyzhang says:

    you may also want to check out vtd-xml, the latest and most advanced xml processing model


  3. Δημήτρης says:

    Thanks!Your way is helpful for me!

    Keep writting java code!!!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: