XML Made Simple with JDOM

Written By: James Williams

- 03 Apr 2006 -
















Description: JDOM is an open-source API to manipulate and create XML documents. Unlike SAX and Xerces on which it is built, it has a simplier, more intuitive API.

  1. XML Made Simple with JDOM

What is it?

JDOM is an open-source API to manipulate and create XML documents. Unlike SAX and Xerces on which it is built, it has a simplier, more intuitive API. This is not meant to be an exhaustive tutorial. It's merely a overview of the things I use 95% of the time.

Creating a document

First, we need inport the JDOM classes and java.io for file functions:

import java.io.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*; 

Creating a document is fairly straightforward. We just instantiate the Document class

Document doc = new Document():

XML Document:


      

Adding Content

XML nodes are represented by the Element class. Elements allow you to add content lists holding more Elements, add attributes, and directly manipulate the text contents. Let's add a root element:

Element root = new Element("root");
doc.setRootElement(root);

XML Document:

/>

When adding elements, we add them to the element that will be it's parent and the Document updates itself. Let's add a sandwich element with a text value of Ham & Cheese:

Element hamCheese = new Element("sandwich");
hamCheese.setText("Ham & Cheese");
root.addContent(hamCheese);

XML Document:

>
     > Ham & Cheese>
>

Let's add one more and add an attribute:

Element pbj = new Element ("sandwich");
pbj.setText("Peanut Butter & Jelly");
Attribute bread = new Attribute("bread", "white");
pbj.setAttribute(bread);
root.addContent(pbj);

XML Document:

>
    >Ham & Cheese>
     bread="white">Peanut Butter & Jelly>
>

Retrieving Content

The most common ways to get content is to use getChild and getChildren. getChild will return the first element whose node name matches the string passed and getChildren returns a List of the elements matching that name.

Element hc = root.getChild("sandwich");
List  sandwiches = root.getChildren("sandwich");
or 
List sandwiches = root.getChildren("sandwich");    //For Java <1.5 

Reading and Writing Files

An XML file can be read in as little as 2 lines of code.

SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File("sandwiches.xml"));

Writing is just as simple. A format can be designated but for most instances, the pretty format is best. It puts each element on a separate line and inserts tabs.

XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(doc, new FileWriter("mysandwiches.xml"));