Free, independent guides since 2010

Code

Reading and parsing XML with dom4j

How to read XML with dom4j: parsing files and strings with SAXReader, walking elements and attributes, handling encodings and dealing with parse errors.

<guide section="Code" type="guide" read="3 min"/>

Almost every dom4j program starts the same way: you get XML from somewhere and turn it into a Document. This guide shows the safest way to do that, how to move around the resulting tree and how to handle the problems you will run into sooner or later. New to the library? Start with our introduction to dom4j.

Our example file

All examples below use this small file, saved as books.xml:

XML
<?xml version="1.0" encoding="UTF-8"?>
<library city="Antwerp">
  <book id="b1" lang="en">
    <title>Web hosting explained</title>
    <author>Sander</author>
    <price currency="EUR">19.95</price>
  </book>
  <book id="b2" lang="nl">
    <title>Zelf een website maken</title>
    <author>Hannes</author>
    <price currency="EUR">24.50</price>
  </book>
</library>

Reading a file with SAXReader

SAXReader is dom4j’s main parser. Since version 2.1.3, the static factory method createDefault() returns a reader with secure defaults: external entities are not resolved. Use it unless you have a very good reason not to.

Java
import java.io.File;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

SAXReader reader = SAXReader.createDefault();
Document document = reader.read(new File("books.xml"));

read() also accepts a URL, an InputStream, a Reader or an InputSource. When you read from a stream, the parser detects the encoding from the XML declaration; when you read from a Reader, the characters are already decoded, so make sure you created the reader with the right charset.

Parsing XML from a string

For small snippets – an API response, a value from a database – DocumentHelper.parseText() is the quickest route:

Java
Document doc = DocumentHelper.parseText("<status code='200'>OK</status>");
String code = doc.getRootElement().attributeValue("code"); // "200"

Walking the tree

Once you have a document, navigation is plain Java. The most useful methods on Element are:

MethodReturns
getRootElement() (on Document)The top-level element
elements() / elements("book")A list of all child elements, or only those with that name
element("title")The first child with that name, or null
elementText("title")The text of that child, or null
getText() / getTextTrim()The element’s own text, raw or trimmed
attributeValue("id")The attribute value, or null
getName(), getParent(), getPath()Name, parent element and an XPath-style location
Java
Element library = document.getRootElement();
System.out.println("Library in " + library.attributeValue("city"));

for (Element book : library.elements("book")) {
    String title  = book.elementText("title");
    String author = book.elementText("author");
    Element price = book.element("price");
    System.out.printf("%s by %s – %s %s%n",
        title, author, price.attributeValue("currency"), price.getTextTrim());
}

Need to visit every element, however deep? A small recursive method does the job, or you can implement the Visitor interface and call document.accept(visitor).

Java
static void walk(Element element, int depth) {
    System.out.println("  ".repeat(depth) + element.getName());
    for (Element child : element.elements()) {
        walk(child, depth + 1);
    }
}

Handling errors

Malformed XML throws a DocumentException. Its message usually contains the line and column, which is exactly what you want to show in a log or an error message:

Java
try {
    Document doc = reader.read(new File("books.xml"));
} catch (DocumentException e) {
    System.err.println("Could not read books.xml: " + e.getMessage());
}

Large files

dom4j loads the whole document into memory. For very large files you can register an ElementHandler on the reader: it is called for each matching element while the file is read, and you can detach() the element afterwards to keep memory use low. For truly huge files a streaming API like StAX is the better choice.

Next step: search your document with XPath in dom4j, or learn how to create and write XML. Before you parse XML from users or other systems, read our page on secure XML parsing.

Frequently asked questions

What is the difference between SAXReader and DocumentHelper.parseText()?

Both build the same Document tree. SAXReader reads from files, URLs, streams and readers; DocumentHelper.parseText() is a shortcut for XML you already have as a String.

Why does my parser return null for an element?

element("name") returns null when there is no direct child with that name. Check spelling, letter case and namespaces – an element in a default namespace is not found by a plain name in XPath.