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.
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 /axis::node-test[predicate]/catalog/book[price < 46]/titlecatalogbooktitle
Every expression evaluates to one of four types: a node-set, a string, a number (always a doublejavax.xml.xpathDocumentBuilder
| Short form | Full form | Meaning |
|---|---|---|
book | child::book | book |
//book | /descendant-or-self::node()/child::book | book |
@id | attribute::id | The id |
. | self::node() | The context node itself |
.. | parent::node() | Its parent |
book[2] | child::book[position()=2] | The second book |
| XPath type | XPathConstants | Java type | evaluateExpression |
|---|---|---|---|
| node-set | NODESETNODE | NodeListNode | XPathNodesNode |
| string | STRING | String | String |
| number | NUMBER | Double | DoubleIntegerLong |
| boolean | BOOLEAN | Boolean | Boolean |
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
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 XPathXPathFactoryevaluate(expression, node)evaluate(expression, node, XPathConstants.NODESET)evaluateExpression(expression, node, type)
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:
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
| Expression | Meaning |
|---|---|
//book | Every book |
//book[@lang='de']/@id | The idlang |
//book[price < 46]/title | Titles 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
gives 134.89000000000001 rather than 134.89. Round or usesum(//price) on the Java side for money.BigDecimal - Two traps in one line:
matches three nodes but returns only the text of the first one, without any warning. Ask for aevaluate("//title") when more than one node may match.NODESET - Expressions are compiled on every call. For an expression used many times, call
once and reuse thexp.compile(expression) . NeitherXPathExpression norXPath is thread-safe.XPathExpression
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
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:
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
, which is always true, so all 3 books matched. Withor '1'='1' and an$who , the input is only ever a value, so it matches nothing, while a real author name still works.XPathVariableResolver - With
on the root, every element is in that namespace, andxmlns="urn:example:books" (which means "book in no namespace") finds 0. XPath 1.0 has no default namespace, so you must bind a prefix with a//book and writeNamespaceContext . The document must also be parsed with//b:book , whichsetNamespaceAware(true) does not do by default.DocumentBuilderFactory
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
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:
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
found the 2 books after b1, andfollowing-sibling::book walked up from Tim Peierls'ancestor::*[last()] element to the outermost element,author .catalog went one level up, to his book's title...- XPath 1.0 has no
or regular expressions.upper-case maps characters one to one, which upper-cases ASCII letters only, andtranslate extracted the first name "Joshua".substring-before is NaN, not an error.number('abc') - 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,/ returned 45.00, the first price in the whole document, not b3's 39.99. Use//price orprice for paths relative to the context node; this mistake silently returns wrong data in loops over nodes..//price - Trap 2: comparing a node-set with a value is true if any node matches. Both
and//author = 'Tim Peierls' were true, because there are authors that are and authors that are not Tim. For "no author is Tim", write//author != 'Tim Peierls' .not(//author = 'Tim Peierls') - Trap 3:
and< convert both sides to numbers.> still compared numerically and matched 2 books, whileprice < '46' is false, because both strings become NaN. XPath 1.0 cannot compare strings alphabetically.'b' < 'c'
Typed results, extension functions and secure processing
Java 9 added evaluateExpression
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:
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.
returned anevaluateExpression("count(//book)", doc, Integer.class) directly, andInteger isXPathNodes , so the ids could be read in a for-each loop. With no type argument, the result is anIterable<Node> that reports what the expression produced: a boolean for the comparison, node-sets of 1 and 4 for the paths.XPathEvaluationResult- An
madeXPathFunctionResolver available; the prefix is bound through aext:upper . Node-set arguments arrive as aNamespaceContext , so the function reads the first node's text, and the German title came back in capitals.NodeList - With
, 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.FEATURE_SECURE_PROCESSING
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.
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:
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
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.user - 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
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.HashMap - 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
| Situation | Use |
|---|---|
| A few values from a small or medium document | XPath with evaluateevaluateExpression |
| Expressions with user input | A compiled expression with $variables |
| Namespaced documents | A namespace-aware parser plus a NamespaceContext |
| Paths relative to a node in a loop | ./child.//descendant// |
| Thousands of lookups on one document | One XPath pass into a Map |
| Expressions from outside your code | FEATURE_SECURE_PROCESSING |
| Regular expressions, XPath 2.0 or 3.1 features | The Saxon library; the JDK implements XPath 1.0 only |
| Files too large for memory |
For the tree XPath runs on, see the