Free, independent guides since 2010

Code

Using XPath with dom4j

How to query XML with XPath in dom4j: selectNodes, selectSingleNode and valueOf, attribute filters, XPath functions, compiled expressions and namespaces.

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

XPath is a small query language for XML: think of it as file paths for elements, with filters and functions on top. dom4j has XPath built into its API, which is one of the main reasons developers choose it. This guide uses the books.xml file from our parsing guide.

Before you start: add Jaxen

dom4j uses the Jaxen engine to evaluate XPath expressions, but declares it as an optional dependency. That means it is not pulled in automatically. Add jaxen:jaxen to your build (see the installation section), otherwise the first call to selectNodes() fails with a NoClassDefFoundError.

The three methods you will use most

Java
// All matching nodes
List<Node> titles = document.selectNodes("//book/title");

// The first match (or null)
Node firstAuthor = document.selectSingleNode("/library/book[1]/author");

// The string value of an expression
String city = document.valueOf("/library/@city");          // "Antwerp"
Number count = document.numberValueOf("count(//book)");    // 2

These methods exist on every Node, so you can also run a query relative to an element: book.valueOf("title") returns the title of that specific book.

Useful XPath patterns

ExpressionSelects
/library/bookAll book elements directly under the root
//titleEvery title element, at any depth
//book[@lang='en']Books with lang="en"
//book[price > 20]Books with a price above 20
//book[last()]The last book
//book/@idThe id attributes themselves
//book[contains(title, 'XML')]Books whose title contains “XML”
sum(//price)The total of all prices
Java
for (Node node : document.selectNodes("//book[@lang='en']")) {
    Element book = (Element) node;
    System.out.println(book.valueOf("title") + " (" + book.valueOf("@id") + ")");
}

Compiling expressions you reuse

If you run the same expression many times – for example on every record in a loop – compile it once with DocumentHelper.createXPath(). That saves parsing the expression again and again.

Java
XPath priceOf = DocumentHelper.createXPath("number(price)");
for (Element book : document.getRootElement().elements("book")) {
    double price = priceOf.numberValueOf(book).doubleValue();
}

Working with namespaces

This is where most people get stuck. Consider an RSS or Atom feed, a sitemap or a SOAP message: their elements live in a namespace, often declared as a default with xmlns="…". In XPath 1.0 an unprefixed name never matches an element in a namespace, so //url/loc on a sitemap returns nothing. The fix is to map a prefix of your choice to the namespace URI:

Java
Map<String, String> ns = Map.of("s", "http://www.sitemaps.org/schemas/sitemap/0.9");

XPath locs = DocumentHelper.createXPath("//s:url/s:loc");
locs.setNamespaceURIs(ns);

for (Node loc : locs.selectNodes(sitemapDocument)) {
    System.out.println(loc.getText());
}

Performance tips

  • Avoid // at the start of an expression on big documents when you know the path: /library/book is faster than //book.
  • Query relative to an element you already have instead of searching the whole document again.
  • For simple “give me the children named x” cases, the plain Java method element.elements("x") is faster than XPath.

Now that you can find what you need, learn how to create and write XML with dom4j.

Frequently asked questions

Why do I get a NoClassDefFoundError for org/jaxen?

dom4j declares Jaxen as an optional dependency. Add jaxen:jaxen to your Maven or Gradle build and the XPath methods will work.

Why does my XPath return nothing on an XML file with xmlns?

The elements are in a namespace. Create an XPath with DocumentHelper.createXPath(), map a prefix to the namespace URI with setNamespaceURIs() and use that prefix in your expression.