XPath in Java: Expressions, Variables and Namespaces

XPath is a small query language for XML: an expression such as //book[price < 46]/title finds nodes by path and condition, replacing loops over a DOM tree. Java evaluates XPath 1.0 expressions through javax.xml.xpath. This page explains how paths and result types work, then runs queries, axes, the traps in context and comparisons, variables, namespaces, extension functions and a speed comparison with plain DOM code.

Share

Contents

How XPath works

XPath is a query language for the tree that an XML parser builds. An expression is a location path: a series of steps separated by /, each of the form axis::node-test[predicate]. The axis says which direction to look from the current node, such as children, descendants, the parent, siblings or attributes. The node test says which nodes to keep, and predicates in square brackets filter them further. /catalog/book[price < 46]/title reads as: from the root, the catalog child, its book children whose price is below 46, and their title children.

Every expression evaluates to one of four types: a node-set, a string, a number (always a double) or a boolean. Java's javax.xml.xpath API, part of JAXP since Java 5, implements XPath 1.0 over a DOM tree, so the document is parsed with DocumentBuilder first and the whole tree is in memory.

XPath abbreviations and their full forms
Short formFull formMeaning
bookchild::bookbook children of the context node
//book/descendant-or-self::node()/child::bookbook elements anywhere in the document
@idattribute::idThe id attribute
.self::node()The context node itself
..parent::node()Its parent
book[2]child::book[position()=2]The second book child (positions start at 1)
Java result types for evaluate
XPath typeXPathConstantsJava typeevaluateExpression (Java 9+)
node-setNODESET, NODENodeList, NodeXPathNodes, Node
stringSTRING (the default)StringString
numberNUMBERDoubleDouble, Integer, Long
booleanBOOLEANBooleanBoolean

All programs use only the JDK and were run on JDK 21.

The sample document

All programs query the same catalog of three books. The third book has two authors and the second is in German, so that conditions on counts and attributes have something to find. The helper disallows DOCTYPE to keep parsing safe; see the DOM parser page for why.

Java
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

final class Catalog {
    private Catalog() {
    }

    static final String XML = """
            <catalog>
              <book id="b1" lang="en"><title>Effective Java</title><price>45.00</price>
                <author>Joshua Bloch</author></book>
              <book id="b2" lang="de"><title>Java ist auch eine Insel</title><price>49.90</price>
                <author>Christian Ullenboom</author></book>
              <book id="b3" lang="en"><title>Java Concurrency in Practice</title>
                <price>39.99</price><author>Brian Goetz</author><author>Tim Peierls</author></book>
            </catalog>
            """;

    static Document parse(String xml, boolean namespaceAware) throws Exception {
        DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
        f.setNamespaceAware(namespaceAware);
        f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        return f.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
    }
}

Writing queries

An XPath object comes from XPathFactory. evaluate(expression, node) returns a string, evaluate(expression, node, XPathConstants.NODESET) returns matching nodes, and evaluateExpression(expression, node, type) (Java 9) returns a typed result.

Java
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class XPathQueries {

    public static void main(String[] args) throws Exception {
        Document doc = Catalog.parse(Catalog.XML, false);
        XPath xp = XPathFactory.newInstance().newXPath();

        // Typed results with evaluateExpression (Java 9+)
        System.out.println("count(//book)          = "
                + xp.evaluateExpression("count(//book)", doc, Integer.class));
        System.out.println("sum(//price)           = "
                + xp.evaluateExpression("sum(//price)", doc, Double.class));
        System.out.println("//book[@lang='de']/@id = "
                + xp.evaluate("//book[@lang='de']/@id", doc));

        // A predicate with a numeric comparison, returning several nodes
        NodeList cheap = (NodeList) xp.evaluate("//book[price < 46]/title", doc,
                XPathConstants.NODESET);
        for (int i = 0; i < cheap.getLength(); i++) {
            System.out.println("under 46: " + cheap.item(i).getTextContent());
        }

        // Functions and positions
        System.out.println("books with 2+ authors  = "
                + xp.evaluate("//book[count(author) >= 2]/title", doc));
        System.out.println("last book's id         = " + xp.evaluate("//book[last()]/@id", doc));
        System.out.println("titles containing Java = "
                + xp.evaluateExpression("count(//title[contains(., 'Java')])", doc,
                        Integer.class));

        // evaluate() returns the string value of only the FIRST matching node
        System.out.println("evaluate(\"//title\")    = " + xp.evaluate("//title", doc));
    }
}

Output:

Output
count(//book)          = 3
sum(//price)           = 134.89000000000001
//book[@lang='de']/@id = b2
under 46: Effective Java
under 46: Java Concurrency in Practice
books with 2+ authors  = Java Concurrency in Practice
last book's id         = b3
titles containing Java = 3
evaluate("//title")    = Effective Java
The expressions used above
ExpressionMeaning
//bookEvery book element at any depth
//book[@lang='de']/@idThe id attribute of books whose lang is "de"
//book[price < 46]/titleTitles of books whose price, compared as a number, is below 46
//book[count(author) >= 2]Books with at least two authors
//book[last()]The last book
contains(., 'Java')True if the current node's text contains "Java"
  • XPath 1.0 numbers are doubles, so sum(//price) gives 134.89000000000001 rather than 134.89. Round or use BigDecimal on the Java side for money.
  • Two traps in one line: evaluate("//title") matches three nodes but returns only the text of the first one, without any warning. Ask for a NODESET when more than one node may match.
  • Expressions are compiled on every call. For an expression used many times, call xp.compile(expression) once and reuse the XPathExpression. Neither XPath nor XPathExpression is thread-safe.

Variables against injection, and namespaces

Building an expression by pasting in user input has the same problem as SQL injection. The program searches by author with the input x' or '1'='1, first by concatenation and then through an XPath variable. It then queries a version of the catalog that has a default namespace.

Java
import java.util.Iterator;
import java.util.List;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class VariablesAndNamespaces {

    static int matches(XPath xp, String expr, Document doc) throws Exception {
        return ((NodeList) xp.evaluate(expr, doc, XPathConstants.NODESET)).getLength();
    }

    public static void main(String[] args) throws Exception {
        Document doc = Catalog.parse(Catalog.XML, false);
        XPath xp = XPathFactory.newInstance().newXPath();

        // Building the expression from input allows XPath injection
        String input = "x' or '1'='1";
        System.out.println("concatenated query, books found: "
                + matches(xp, "//book[author='" + input + "']", doc));

        // A variable is always treated as a value, never as part of the expression
        xp.setXPathVariableResolver(name -> name.getLocalPart().equals("who") ? input : null);
        System.out.println("query with $who, books found:    "
                + matches(xp, "//book[author=$who]", doc));
        xp.setXPathVariableResolver(name -> "Brian Goetz");
        System.out.println("$who = Brian Goetz, books found: "
                + matches(xp, "//book[author=$who]", doc));

        // Documents with a default namespace need a prefix in the expression
        Document ns = Catalog.parse(Catalog.XML.replace("<catalog>",
                "<catalog xmlns=\"urn:example:books\">"), true);
        XPath plain = XPathFactory.newInstance().newXPath();
        System.out.println("namespaced doc, //book:        " + matches(plain, "//book", ns));

        XPath withNs = XPathFactory.newInstance().newXPath();
        withNs.setNamespaceContext(new NamespaceContext() {
            @Override
            public String getNamespaceURI(String prefix) {
                return prefix.equals("b") ? "urn:example:books" : null;
            }

            @Override
            public String getPrefix(String uri) {
                return null;
            }

            @Override
            public Iterator<String> getPrefixes(String uri) {
                return List.<String>of().iterator();
            }
        });
        System.out.println("namespaced doc, //b:book:      " + matches(withNs, "//b:book", ns));
    }
}

Output:

Output
concatenated query, books found: 3
query with $who, books found:    0
$who = Brian Goetz, books found: 1
namespaced doc, //book:        0
namespaced doc, //b:book:      3
  • Concatenated, the input closes the string and adds or '1'='1', which is always true, so all 3 books matched. With $who and an XPathVariableResolver, the input is only ever a value, so it matches nothing, while a real author name still works.
  • With xmlns="urn:example:books" on the root, every element is in that namespace, and //book (which means "book in no namespace") finds 0. XPath 1.0 has no default namespace, so you must bind a prefix with a NamespaceContext and write //b:book. The document must also be parsed with setNamespaceAware(true), which DocumentBuilderFactory does not do by default.

Axes, functions and three traps

Beyond child paths, XPath can walk in every direction and has a small function library. The program uses the catalog's two-author book, because axes such as ancestor and comparisons on repeated elements behave differently from what most people expect.

Java
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class AxesAndTraps {

    public static void main(String[] args) throws Exception {
        Document doc = Catalog.parse(Catalog.XML, false);
        XPath xp = XPathFactory.newInstance().newXPath();

        // Axes: directions other than "down"
        System.out.println("following-sibling of b1: " + xp.evaluate(
                "count(//book[@id='b1']/following-sibling::book)", doc));
        System.out.println("ancestor of Tim's author: " + xp.evaluate(
                "name(//author[.='Tim Peierls']/ancestor::*[last()])", doc));
        System.out.println("book of Tim Peierls: " + xp.evaluate(
                "//author[.='Tim Peierls']/../title", doc));
        System.out.println("second author of b3: " + xp.evaluate(
                "//book[@id='b3']/author[position()=2]", doc));

        // String and number functions
        System.out.println("substring-before: " + xp.evaluate(
                "substring-before(//book[1]/author, ' ')", doc));
        System.out.println("upper-case via translate: " + xp.evaluate(
                "translate(//book[1]/title, 'abcdefghijklmnopqrstuvwxyz',"
                + " 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')", doc));
        System.out.println("number('abc'): " + xp.evaluate("number('abc')", doc)
                + ", as Double: " + xp.evaluate("number('abc')", doc, XPathConstants.NUMBER));

        // Trap 1: '//' always starts at the document root, even with a book as context
        Node b3 = (Node) xp.evaluate("//book[@id='b3']", doc, XPathConstants.NODE);
        System.out.println("context b3, '//price': " + xp.evaluate("//price", b3)
                + "   <- the first price in the document");
        System.out.println("context b3, 'price':   " + xp.evaluate("price", b3));
        System.out.println("context b3, './/price': " + xp.evaluate(".//price", b3));

        // Trap 2: comparing a node-set is true if ANY node matches
        System.out.println("//author = 'Tim Peierls':  " + xp.evaluate(
                "//author = 'Tim Peierls'", doc));
        System.out.println("//author != 'Tim Peierls': " + xp.evaluate(
                "//author != 'Tim Peierls'", doc) + "   <- also true");
        System.out.println("not(//author = 'Tim Peierls'): " + xp.evaluate(
                "not(//author = 'Tim Peierls')", doc));

        // Trap 3: string comparison with < converts both sides to numbers
        NodeList cheap = (NodeList) xp.evaluate("//book[price < '46']/@id", doc,
                XPathConstants.NODESET);
        System.out.println("price < '46' (string literal) matched " + cheap.getLength()
                + " books; 'b' < 'c' is " + xp.evaluate("'b' < 'c'", doc));
    }
}

Output:

Output
following-sibling of b1: 2
ancestor of Tim's author: catalog
book of Tim Peierls: Java Concurrency in Practice
second author of b3: Tim Peierls
substring-before: Joshua
upper-case via translate: EFFECTIVE JAVA
number('abc'): NaN, as Double: NaN
context b3, '//price': 45.00   <- the first price in the document
context b3, 'price':   39.99
context b3, './/price': 39.99
//author = 'Tim Peierls':  true
//author != 'Tim Peierls': true   <- also true
not(//author = 'Tim Peierls'): false
price < '46' (string literal) matched 2 books; 'b' < 'c' is false
  • following-sibling::book found the 2 books after b1, and ancestor::*[last()] walked up from Tim Peierls' author element to the outermost element, catalog. .. went one level up, to his book's title.
  • XPath 1.0 has no upper-case or regular expressions. translate maps characters one to one, which upper-cases ASCII letters only, and substring-before extracted the first name "Joshua". number('abc') is NaN, not an error.
  • Trap 1: an expression that starts with // or / always starts at the document root, even when the context node is a book. With b3 as context, //price returned 45.00, the first price in the whole document, not b3's 39.99. Use price or .//price for paths relative to the context node; this mistake silently returns wrong data in loops over nodes.
  • Trap 2: comparing a node-set with a value is true if any node matches. Both //author = 'Tim Peierls' and //author != 'Tim Peierls' were true, because there are authors that are and authors that are not Tim. For "no author is Tim", write not(//author = 'Tim Peierls').
  • Trap 3: < and > convert both sides to numbers. price < '46' still compared numerically and matched 2 books, while 'b' < 'c' is false, because both strings become NaN. XPath 1.0 cannot compare strings alphabetically.

Typed results, extension functions and secure processing

Java 9 added evaluateExpression, which returns a typed result without casts, and the API has always allowed Java methods to be called from expressions. The program uses both, then shows how secure processing changes the second.

Java
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathEvaluationResult;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathFunction;
import javax.xml.xpath.XPathNodes;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Extensions {

    static final String EXT = "urn:example:ext";

    static XPath withUpper(XPathFactory f) {
        XPath xp = f.newXPath();
        xp.setNamespaceContext(new NamespaceContext() {
            @Override
            public String getNamespaceURI(String prefix) {
                return "ext".equals(prefix) ? EXT : XMLConstants.NULL_NS_URI;
            }

            @Override
            public String getPrefix(String uri) {
                return null;
            }

            @Override
            public java.util.Iterator<String> getPrefixes(String uri) {
                return null;
            }
        });
        // ext:upper(string) implemented in Java
        xp.setXPathFunctionResolver((QName name, int arity) -> {
            if (EXT.equals(name.getNamespaceURI()) && name.getLocalPart().equals("upper")
                    && arity == 1) {
                XPathFunction upper = (List<?> fnArgs) -> {
                    Object arg = fnArgs.get(0);              // a node-set arrives as NodeList
                    String text = arg instanceof NodeList nl ? (nl.getLength() == 0 ? ""
                            : nl.item(0).getTextContent()) : String.valueOf(arg);
                    return text.toUpperCase();
                };
                return upper;
            }
            return null;
        });
        return xp;
    }

    public static void main(String[] args) throws Exception {
        Document doc = Catalog.parse(Catalog.XML, false);

        // Java 9+: evaluateExpression returns typed results, or XPathEvaluationResult for ANY
        XPath xp = XPathFactory.newInstance().newXPath();
        Double total = xp.evaluateExpression("sum(//price)", doc, Double.class);
        Integer count = xp.evaluateExpression("count(//book)", doc, Integer.class);
        XPathNodes ids = xp.evaluateExpression("//book/@id", doc, XPathNodes.class);
        StringBuilder sb = new StringBuilder();
        for (Node n : ids) {                                  // XPathNodes is Iterable
            sb.append(n.getNodeValue()).append(' ');
        }
        System.out.println("typed: sum=" + total + ", count=" + count + ", ids=" + sb.toString()
                .trim());
        for (String expr : new String[] {"count(//author) > 3", "//book[2]/title",
            "//author"}) {
            XPathEvaluationResult<?> r = xp.evaluateExpression(expr, doc);
            System.out.println("ANY " + expr + " -> " + r.type() + (r.type()
                    == XPathEvaluationResult.XPathResultType.NODESET ? " of "
                    + ((XPathNodes) r.value()).size() : " " + r.value()));
        }

        // Extension functions: allowed with a default factory
        XPathFactory open = XPathFactory.newInstance();
        System.out.println("ext:upper: " + withUpper(open).evaluate(
                "ext:upper(//book[@id='b2']/title)", doc));

        // Secure processing turns extension functions off
        XPathFactory secure = XPathFactory.newInstance();
        secure.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        try {
            withUpper(secure).evaluate("ext:upper(//book[1]/title)", doc);
        } catch (XPathExpressionException e) {
            String msg = String.valueOf(e.getMessage() != null ? e.getMessage()
                    : e.getCause());
            System.out.println("with FEATURE_SECURE_PROCESSING: " + msg.lines().findFirst()
                    .orElse(""));
        }
    }
}

Output:

Output
typed: sum=134.89000000000001, count=3, ids=b1 b2 b3
ANY count(//author) > 3 -> BOOLEAN true
ANY //book[2]/title -> NODESET of 1
ANY //author -> NODESET of 4
ext:upper: JAVA IST AUCH EINE INSEL
with FEATURE_SECURE_PROCESSING: Extension function: '{urn:example:ext}upper' can not be invoked when the XMLConstants.FEATURE_SECURE_PROCESSING feature is set to true.
  • evaluateExpression("count(//book)", doc, Integer.class) returned an Integer directly, and XPathNodes is Iterable<Node>, so the ids could be read in a for-each loop. With no type argument, the result is an XPathEvaluationResult that reports what the expression produced: a boolean for the comparison, node-sets of 1 and 4 for the paths.
  • An XPathFunctionResolver made ext:upper available; the prefix is bound through a NamespaceContext. Node-set arguments arrive as a NodeList, so the function reads the first node's text, and the German title came back in capitals.
  • With FEATURE_SECURE_PROCESSING, the same call failed: extension functions are disabled because they let an expression run arbitrary Java code. Enable secure processing whenever expressions come from outside your code.

How fast is XPath?

XPath is convenient, but each evaluation walks the DOM tree, and the JDK's implementation also converts the tree into its own internal model. The program looks up 500 users by id in a document of 2,000 users four ways. Each way runs 4 times; the first is a warm-up and the best of the remaining 3 is shown. This is a rough comparison on a 2-CPU Linux machine with JDK 21.

Java
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XPathSpeed {

    interface Lookup {
        String run(int id) throws Exception;
    }

    static long time(Lookup lookup, int n) throws Exception {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 4; run++) {                    // run 0 is a warm-up
            long t0 = System.nanoTime();
            for (int i = 0; i < n; i++) {
                if (lookup.run(i * 7 % 2000).isEmpty()) {
                    throw new AssertionError();
                }
            }
            if (run > 0) {
                best = Math.min(best, System.nanoTime() - t0);
            }
        }
        return best / 1000000;
    }

    public static void main(String[] args) throws Exception {
        StringBuilder sb = new StringBuilder("<users>");
        for (int i = 0; i < 2000; i++) {
            sb.append("<user id=\"").append(i).append("\"><name>user").append(i)
                    .append("</name></user>");
        }
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new StringReader(sb.append("</users>").toString())));
        XPath xp = XPathFactory.newInstance().newXPath();
        int n = 500;
        System.out.println(n + " lookups by id in a document of 2,000 users, best of 3");

        long evaluate = time(id -> xp.evaluate("/users/user[@id='" + id + "']/name", doc), n);
        int[] current = new int[1];
        xp.setXPathVariableResolver(q -> String.valueOf(current[0]));
        XPathExpression withVar = xp.compile("/users/user[@id=$id]/name");
        long compiledTime = time(id -> {
            current[0] = id;
            return withVar.evaluate(doc);
        }, n);
        NodeList users = doc.getElementsByTagName("user");
        long domLoop = time(id -> {
            String wanted = String.valueOf(id);
            for (int i = 0; i < users.getLength(); i++) {
                Element u = (Element) users.item(i);
                if (u.getAttribute("id").equals(wanted)) {
                    return u.getElementsByTagName("name").item(0).getTextContent();
                }
            }
            return "";
        }, n);
        java.util.Map<String, String> index = new java.util.HashMap<>();
        NodeList all = (NodeList) xp.evaluate("/users/user", doc, XPathConstants.NODESET);
        for (int i = 0; i < all.getLength(); i++) {
            Element u = (Element) all.item(i);
            index.put(u.getAttribute("id"), u.getElementsByTagName("name").item(0)
                    .getTextContent());
        }
        long mapLookup = time(id -> index.get(String.valueOf(id)), n);
        System.out.printf("xp.evaluate(string) each time:  %5d ms%n", evaluate);
        System.out.printf("compiled once, with $id:        %5d ms%n", compiledTime);
        System.out.printf("plain DOM loop:                 %5d ms%n", domLoop);
        System.out.printf("one XPath pass into a HashMap:  %5d ms%n", mapLookup);
    }
}

Output of the lookup comparison:

Output
500 lookups by id in a document of 2,000 users, best of 3
xp.evaluate(string) each time:    246 ms
compiled once, with $id:          176 ms
plain DOM loop:                     9 ms
one XPath pass into a HashMap:      0 ms
  • A plain DOM loop over the user elements was several times faster than any XPath variant, even though both scan the users one by one. Most of XPath's time goes into evaluation overhead rather than the scan itself.
  • Compiling once and passing the id as a variable was only somewhat faster than compiling a new string each time; it is still the right habit, because it also prevents XPath injection.
  • When many lookups run against the same document, one XPath pass that builds a HashMap turns each lookup into a hash lookup that did not register on the millisecond clock. Building the map is a one-time cost not included above.
  • For a handful of queries on a configuration file, none of this matters; XPath's clarity wins. In loops over thousands of nodes, prefer DOM methods or an index.

Which approach to use

Choosing a way to find data in XML
SituationUse
A few values from a small or medium documentXPath with evaluate or evaluateExpression
Expressions with user inputA compiled expression with $variables
Namespaced documentsA namespace-aware parser plus a NamespaceContext
Paths relative to a node in a loop./child or .//descendant, never //
Thousands of lookups on one documentOne XPath pass into a Map, or DOM methods
Expressions from outside your codeFEATURE_SECURE_PROCESSING on the factory
Regular expressions, XPath 2.0 or 3.1 featuresThe Saxon library; the JDK implements XPath 1.0 only
Files too large for memoryStAX; XPath needs a DOM tree

For the tree XPath runs on, see the DOM parser page.