JDOM: Document Object Model Library
When working with XML in Java, developers have several options: DOM, SAX, StAX, and JDOM. While the standard W3C DOM API is powerful, it was designed to be language-neutral, which often makes it feel clunky and verbose in Java. JDOM addresses this by providing an XML processing library built specifically for Java, embracing Java idioms like collections, generics, and the for-each loop.
What is JDOM?
JDOM (Java Document Object Model) is an open-source library that represents an XML document as a tree of Java objects in memory. Unlike the W3C DOM, JDOM is not an interface-based abstraction layer—it uses concrete classes and leverages the Java Collections Framework, making it intuitive for Java developers.
Key benefits include:
-
Java-friendly API using
Listand standard collections. - Lightweight and fast for small to medium documents.
- Easy integration with SAX and DOM when needed.
- Simple document creation and manipulation.
Adding JDOM to Your Project
For JDOM 2.x, add the following Maven dependency:
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6.1</version>
</dependency>
Reading an XML Document
Let's assume we have the following books.xml file:
<library>
<book id="1">
<title>Effective Java</title>
<author>Joshua Bloch</author>
</book>
<book id="2">
<title>Clean Code</title>
<author>Robert Martin</author>
</book>
</library>
We can parse this file using SAXBuilder, which is the recommended way to build a JDOM document:
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import java.io.File;
import java.util.List;
public class JDOMReader {
public static void main(String[] args) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("books.xml"));
Element root = document.getRootElement();
List<Element> books = root.getChildren("book");
for (Element book : books) {
String id = book.getAttributeValue("id");
String title = book.getChildText("title");
String author = book.getChildText("author");
System.out.printf("Book %s: %s by %s%n", id, title, author);
}
}
}
Notice how getChildren() returns a List<Element>, allowing you to use the enhanced for loop directly. This is a significant readability improvement over the verbose NodeList iteration required by the W3C DOM.
Creating an XML Document
JDOM makes building documents from scratch equally straightforward:
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.FileWriter;
public class JDOMWriter {
public static void main(String[] args) throws Exception {
Element library = new Element("library");
Document document = new Document(library);
Element book = new Element("book");
book.setAttribute("id", "3");
book.addContent(new Element("title").setText("The Pragmatic Programmer"));
book.addContent(new Element("author").setText("Andrew Hunt"));
library.addContent(book);
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(document, new FileWriter("output.xml"));
// Or print to console:
outputter.output(document, System.out);
}
}
The XMLOutputter combined with Format.getPrettyFormat() produces nicely indented, human-readable output. Other format options include getCompactFormat() and getRawFormat().
Modifying Existing Documents
Because JDOM elements are mutable, editing is trivial:
Element root = document.getRootElement();
for (Element book : root.getChildren("book")) {
if ("1".equals(book.getAttributeValue("id"))) {
book.getChild("author").setText("J. Bloch");
}
}
You can also remove nodes using removeChild() or removeContent().
Using XPath with JDOM
JDOM 2 provides robust XPath support through the XPathFactory class:
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
XPathFactory xpFactory = XPathFactory.instance();
XPathExpression<Element> expr = xpFactory.compile(
"//book[@id='2']/title", Filters.element());
Element result = expr.evaluateFirst(document);
System.out.println(result.getText()); // Clean Code
The use of Filters ensures type-safe results, taking advantage of Java generics.
JDOM vs. W3C DOM
| Feature | JDOM | W3C DOM |
|---|---|---|
| API style | Java-native, concrete classes | Interface-based, language-neutral |
| Collections | Java List
|
Custom NodeList
|
| Ease of use | High | Moderate |
| Memory footprint | Moderate | Higher |
| Standard | Not a JCP standard | W3C standard |
When to Use JDOM
JDOM is an excellent choice when:
- You want clean, readable, idiomatic Java code.
- Your documents fit comfortably in memory.
- You need to both read and write XML with minimal boilerplate.
However
Top comments (0)