Querying XML with XPath: Expressions and the XPath API
Locate data in XML with XPath 1.0 from Java: location paths, // and predicates, attributes, axes, unions, functions like count, sum, contains and normalize-space, typed results with evaluateExpression and XPathNodes, compiled expressions, variables against injection, and errors.
kvi5hnuCode Sprout team member10 min readOn this page
Walking a DOM tree by hand to reach one value takes many steps. To get the title of an XHTML page, you'd get the root, find the head child among the whitespace nodes, find title inside it, and read its text. XPath expresses the same thing in one line:
/html/head/title/text()
XPath is a small query language for XML trees, standardized by the W3C. It's also the basis of XSLT (article 47) and is used inside XML Schema keys, many testing tools, and browser developer tools. The JDK implements XPath 1.0. Later versions (2.0, 3.0, 3.1) add sequences, types and many functions, but require a third-party library such as Saxon.
Location paths
An XPath expression usually describes a set of nodes, written as a path of steps separated by /. Each step selects nodes relative to the result of the previous one.
| Expression | Selects |
|---|---|
/library/shelf/book | book children of shelf children of the root element library |
//title | all title elements anywhere in the document |
shelf//author | author descendants (at any depth) of shelf children of the context node |
. and .. | the context node and its parent |
* | any element |
@id, @* | the id attribute, all attributes |
text() | text node children |
node() | any child node |
a | b | the union of two node sets, in document order |
A path that starts with / is absolute. Otherwise it's evaluated relative to a context node, which you choose when calling the API.
Predicates
A step can be filtered with predicates in brackets:
| Expression | Meaning |
|---|---|
book[1], book[last()] | the first and last book child (positions start at 1) |
book[position() > 2] | all but the first two |
book[@lang='en'] | books with that attribute value |
book[price < 30] | books with a price child whose number value is below 30 |
book[author='Ada Lovelace'] | books with some author child equal to that string |
book[count(author) > 1] | books with more than one author |
book[@lang='en' and @year > 2022] | combined conditions (and, or, not(...)) |
title[contains(., 'Java')] | titles whose text contains Java |
Comparisons between a node set and a value are existential: author='Ada Lovelace' is true if any author matches. Comparing with a number converts the node's text to a number, so price < 30 works on the text 24.50.
Axes
Each step actually moves along an axis. / means the child axis, // is short for /descendant-or-self::node()/, @ is the attribute axis, and .. is parent::node(). The full syntax axis::test reaches other directions:
| Axis | Direction |
|---|---|
child, descendant, descendant-or-self | down |
parent, ancestor, ancestor-or-self | up |
following-sibling, preceding-sibling | sideways, same parent |
following, preceding | everything after or before in document order, excluding ancestors and descendants |
attribute, self, namespace | attributes, the node itself, namespace nodes |
For example, //author[.='Alan Turing']/ancestor::shelf/@topic finds the topic of the shelf containing that author.
Functions and values
Besides node sets, XPath 1.0 has three value types: strings, numbers (always double) and booleans. The core function library includes:
| Category | Functions |
|---|---|
| Node sets | count, last, position, name, local-name, namespace-uri, id |
| Strings | string, concat, contains, starts-with, substring, substring-before, substring-after, string-length, normalize-space, translate |
| Numbers | number, sum, floor, ceiling, round, and the operators + - * div mod |
| Booleans | boolean, not, true, false, lang |
Division is written div, because / is the path separator. The string value of an element is the concatenation of all its text, including whitespace, which is why normalize-space is so often useful. There's no ends-with, lower-case or regular expression support in 1.0. Use translate for simple case mapping, or do such work in Java.
The XPath API
Everything lives in javax.xml.xpath. Get an XPath object from a factory:
XPath xpath = XPathFactory.newInstance().newXPath();
The simplest call evaluates an expression and returns its string value:
String title = xpath.evaluate("/html/head/title", doc);
The second argument is the context item: a Document, any Node, or an InputSource that the API parses for you.
For other result types, evaluateExpression (Java 9) takes the desired Java type:
int count = xpath.evaluateExpression("count(//book)", doc, Integer.class);
double total = xpath.evaluateExpression("sum(//price)", doc, Double.class);
boolean any = xpath.evaluateExpression("//book[@year < 2020]", doc, Boolean.class);
Node book = xpath.evaluateExpression("//book[@id='b2']", doc, Node.class);
XPathNodes books = xpath.evaluateExpression("//book", doc, XPathNodes.class);
for (Node n : books) ...
The allowed types are String, Boolean, Integer, Long, Double, Node and XPathNodes. Other classes, even Number, are rejected with IllegalArgumentException. XPathNodes is an Iterable<Node> with size() and get(i), so it works with an enhanced for loop, unlike the older NodeList.
Older code passes a QName constant from XPathConstants instead and casts the result:
var nodes = (NodeList) xpath.evaluate("//book", doc, XPathConstants.NODESET);
var count = (Double) xpath.evaluate("count(//book)", doc, XPathConstants.NUMBER);
When you don't know the result type in advance, for example for an expression typed by a user, call evaluateExpression(expr, item) without a type. You get an XPathEvaluationResult<?>, whose type() is one of STRING, NUMBER, BOOLEAN, NODE or NODESET (or ANY), and whose value() holds the result.
Relative evaluation and compiled expressions
Expressions without a leading / are evaluated against whatever node you pass in. That's the natural way to process records: select them with one expression, then extract fields from each record with relative expressions. When an expression is evaluated many times, compile it once:
XPathExpression titleOf = xpath.compile("normalize-space(title)");
for (Node book : xpath.evaluateExpression("//book", doc, XPathNodes.class))
String title = titleOf.evaluate(book);
XPath and XPathExpression objects aren't thread-safe. Use one per thread.
Variables: avoiding XPath injection
Building an expression by concatenating user input invites the same problem as SQL injection. The input x' or '1'='1 turns //book[author='...'] into a condition that's always true. Use XPath variables instead. Write $name in the expression and supply the values through an XPathVariableResolver:
xpath.setXPathVariableResolver(name -> vars.get(name.getLocalPart()));
XPathExpression byAuthor = xpath.compile("//book[author=$who]");
The variable's value is always treated as a value, never as part of the expression. The resolver is consulted at evaluation time, so a compiled expression can be reused with new values.
An XPathFunctionResolver similarly lets expressions call Java methods as extension functions (in a namespace of your choosing). Since JDK 24, the shipped conf/jaxp.properties sets jdk.xml.enableExtensionFunctions=false. That mainly blocks extension functions that a stylesheet tries to call on its own (article 47). A resolver you install explicitly with setXPathFunctionResolver still works on JDK 25, because your code chose to provide the functions.
Errors and limits
A syntax error or an unknown function raises XPathExpressionException, whose message usually wraps a TransformerException from the underlying implementation. The JDK also limits the complexity of expressions: jdk.xml.xpathExprGrpLimit (groups), jdk.xml.xpathExprOpLimit (operators per expression) and jdk.xml.xpathTotalOpLimit (operators in total, relevant for XSLT). Their defaults in conf/jaxp.properties are 10, 100 and 10,000, and each can be overridden with a system property of the same name. A value of 0 means no limit.
The program
The demo parses a small library catalog and evaluates a long list of expressions, printing the result type and value of each. It then shows typed results, relative evaluation with compiled expressions, the difference between string concatenation and variables, and two errors.
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
public class Solution {
static final String LIBRARY = """
<library name="City Library">
<shelf topic="programming">
<book id="b1" year="2024" lang="en">
<title>Core Topics in Java</title>
<author>Ada Lovelace</author>
<price currency="EUR">39.90</price>
</book>
<book id="b2" year="2019" lang="de">
<title>Algorithmen kompakt</title>
<author>Grace Hopper</author>
<author>Alan Turing</author>
<price currency="EUR">24.50</price>
</book>
</shelf>
<shelf topic="fiction">
<book id="b3" year="2021" lang="en">
<title> The Quiet Compiler </title>
<author>Ada Lovelace</author>
<price currency="USD">12.00</price>
</book>
</shelf>
</library>""";
static XPath xpath = XPathFactory.newInstance().newXPath();
static void show(String expr, Document doc) throws XPathExpressionException {
XPathEvaluationResult<?> result = xpath.evaluateExpression(expr, doc);
String value = switch (result.type()) {
case NODESET -> {
var parts = new ArrayList<String>();
for (Node n : (XPathNodes) result.value()) parts.add(describe(n));
yield parts.toString();
}
case NODE -> describe((Node) result.value());
case NUMBER -> {
double d = ((Number) result.value()).doubleValue();
yield d == Math.rint(d) ? String.valueOf((long) d) : String.valueOf(d);
}
default -> String.valueOf(result.value());
};
System.out.printf("%-52s %-7s %s%n", expr, result.type(), value);
}
static String describe(Node n) {
return switch (n) {
case Attr a -> "@" + a.getName() + "=" + a.getValue();
case Element e when e.getTagName().equals("book") -> "book " + e.getAttribute("id");
case Element e -> "<" + e.getTagName() + ">" + e.getTextContent().strip();
case Text t -> "text \"" + t.getData() + "\"";
default -> n.getNodeName();
};
}
public static void main(String[] args) throws Exception {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(LIBRARY)));
System.out.println("--- paths and predicates ---");
for (String expr : List.of(
"/library/shelf/book/title/text()",
"//title",
"/library/shelf[2]/book",
"//book[1]",
"(//book)[1]",
"//book[last()]/@id",
"//book[@lang='en' and @year > 2022]",
"//book[price < 30]/title",
"//book[count(author) > 1]",
"//book[author='Ada Lovelace']/@id",
"//price/@currency | //book/@lang",
"//shelf[@topic='fiction']//author",
"/library/@name"))
show(expr, doc);
System.out.println("--- axes ---");
for (String expr : List.of(
"//author[.='Alan Turing']/parent::book/@id",
"//author[.='Alan Turing']/ancestor::shelf/@topic",
"//author[.='Alan Turing']/preceding-sibling::author",
"//book[@id='b1']/following::book",
"//book[@id='b2']/child::*[position() > 2]"))
show(expr, doc);
System.out.println("--- functions and scalar results ---");
for (String expr : List.of(
"count(//book)",
"sum(//price[@currency='EUR'])",
"sum(//price) div count(//price)",
"round(sum(//price) div count(//price) * 100) div 100",
"string(//book[@id='b3']/title)",
"normalize-space(//book[@id='b3']/title)",
"concat(//book[1]/author, ' wrote ', //book[1]/title)",
"//title[contains(., 'Java')]",
"//title[starts-with(., 'Algo')]",
"string-length(//book[@id='b2']/title)",
"substring-before(//book[1]/@year, '4')",
"translate('Java', 'av', 'AV')",
"boolean(//book[@lang='fr'])",
"not(//book[@lang='fr'])",
"//nothing"))
show(expr, doc);
System.out.println("--- typed results ---");
String first = xpath.evaluate("//book[1]/title", doc); // String result
int count = xpath.evaluateExpression("count(//author)", doc, Integer.class);
double max = xpath.evaluateExpression("//price[not(. < //price)]", doc, Double.class);
boolean any = xpath.evaluateExpression("//book[@year < 2020]", doc, Boolean.class);
Node node = xpath.evaluateExpression("//book[@id='b2']", doc, Node.class);
var legacy = (NodeList) xpath.evaluate("//author", doc, XPathConstants.NODESET);
System.out.println("evaluate: " + first + "; authors: " + count + "; max price: " + max
+ "; any before 2020: " + any + "; node: " + describe(node) + "; NodeList length: " + legacy.getLength());
System.out.println("--- relative evaluation and compiled expressions ---");
XPathExpression titleOf = xpath.compile("normalize-space(title)");
XPathExpression priceOf = xpath.compile("number(price)");
for (Node book : xpath.evaluateExpression("//book", doc, XPathNodes.class))
System.out.printf("%s: %s, %.2f%n", ((Element) book).getAttribute("id"),
titleOf.evaluate(book), priceOf.evaluateExpression(book, Double.class));
System.out.println("--- variables instead of string concatenation ---");
String userInput = "x' or '1'='1";
String unsafe = "//book[author='" + userInput + "']";
System.out.println("concatenated query matches " + xpath.evaluateExpression("count(" + unsafe + ")", doc, Integer.class) + " books");
XPath safe = XPathFactory.newInstance().newXPath();
Map<String, Object> vars = new HashMap<>(Map.of("who", userInput));
safe.setXPathVariableResolver(name -> vars.get(name.getLocalPart()));
XPathExpression byAuthor = safe.compile("count(//book[author=$who])");
System.out.println("with $who: " + byAuthor.evaluateExpression(doc, Integer.class) + " books");
vars.put("who", "Ada Lovelace");
System.out.println("with $who = Ada Lovelace: " + byAuthor.evaluateExpression(doc, Integer.class) + " books");
System.out.println("--- errors ---");
for (String bad : List.of("//book[", "foo(1)"))
try {
xpath.evaluate(bad, doc);
} catch (XPathExpressionException e) {
String msg = Objects.requireNonNullElse(e.getMessage(), String.valueOf(e.getCause()));
System.out.println(bad + " -> " + e.getClass().getSimpleName() + ": " + msg.lines().findFirst().orElse(""));
}
}
}
--- paths and predicates ---
/library/shelf/book/title/text() NODESET [text "Core Topics in Java", text "Algorithmen kompakt", text " The Quiet Compiler "]
//title NODESET [<title>Core Topics in Java, <title>Algorithmen kompakt, <title>The Quiet Compiler]
/library/shelf[2]/book NODESET [book b3]
//book[1] NODESET [book b1, book b3]
(//book)[1] NODESET [book b1]
//book[last()]/@id NODESET [@id=b2, @id=b3]
//book[@lang='en' and @year > 2022] NODESET [book b1]
//book[price < 30]/title NODESET [<title>Algorithmen kompakt, <title>The Quiet Compiler]
//book[count(author) > 1] NODESET [book b2]
//book[author='Ada Lovelace']/@id NODESET [@id=b1, @id=b3]
//price/@currency | //book/@lang NODESET [@lang=en, @currency=EUR, @lang=de, @currency=EUR, @lang=en, @currency=USD]
//shelf[@topic='fiction']//author NODESET [<author>Ada Lovelace]
/library/@name NODESET [@name=City Library]
--- axes ---
//author[.='Alan Turing']/parent::book/@id NODESET [@id=b2]
//author[.='Alan Turing']/ancestor::shelf/@topic NODESET [@topic=programming]
//author[.='Alan Turing']/preceding-sibling::author NODESET [<author>Grace Hopper]
//book[@id='b1']/following::book NODESET [book b2, book b3]
//book[@id='b2']/child::*[position() > 2] NODESET [<author>Alan Turing, <price>24.50]
--- functions and scalar results ---
count(//book) NUMBER 3
sum(//price[@currency='EUR']) NUMBER 64.4
sum(//price) div count(//price) NUMBER 25.46666666666667
round(sum(//price) div count(//price) * 100) div 100 NUMBER 25.47
string(//book[@id='b3']/title) STRING The Quiet Compiler
normalize-space(//book[@id='b3']/title) STRING The Quiet Compiler
concat(//book[1]/author, ' wrote ', //book[1]/title) STRING Ada Lovelace wrote Core Topics in Java
//title[contains(., 'Java')] NODESET [<title>Core Topics in Java]
//title[starts-with(., 'Algo')] NODESET [<title>Algorithmen kompakt]
string-length(//book[@id='b2']/title) NUMBER 19
substring-before(//book[1]/@year, '4') STRING 202
translate('Java', 'av', 'AV') STRING JAVA
boolean(//book[@lang='fr']) BOOLEAN false
not(//book[@lang='fr']) BOOLEAN true
//nothing NODESET []
--- typed results ---
evaluate: Core Topics in Java; authors: 4; max price: 39.9; any before 2020: true; node: book b2; NodeList length: 4
--- relative evaluation and compiled expressions ---
b1: Core Topics in Java, 39.90
b2: Algorithmen kompakt, 24.50
b3: The Quiet Compiler, 12.00
--- variables instead of string concatenation ---
concatenated query matches 3 books
with $who: 0 books
with $who = Ada Lovelace: 2 books
--- errors ---
//book[ -> XPathExpressionException: javax.xml.transform.TransformerException: A location path was expected, but the end of the XPath expression was found instead.
foo(1) -> XPathExpressionException: javax.xml.transform.TransformerException: Could not find function: foo
Notice that //book[1] returns two books, one per shelf. The string value of the third title keeps its odd spacing until normalize-space cleans it up. And the concatenated query matches all three books, while the same input passed as $who matches none.
Common questions
What's the difference between /, // and .//?
/a selects a children of the root. //a selects every a element anywhere in the document, even when evaluated relative to some node. .//a selects a descendants of the context node only. Forgetting the dot is a common bug in relative evaluation: //title evaluated on one book still returns every title in the document.
Why does my query return nothing on a document with xmlns="..."?
In XPath 1.0, an unprefixed name means "no namespace". Bind a prefix with a NamespaceContext and write //h:body. Article 44 shows how.
How do I get the text of an element without surrounding whitespace?
Use normalize-space(title) in the expression, or strip() in Java on the string result. text() selects only the direct text nodes, which may be split around comments or child elements, so string(title) (or simply title passed to evaluate) is usually what you want.
How do I count nodes or test for existence?
count(//book) returns a number, and boolean(//book[@lang='de']) (or evaluating the path with Boolean.class) tells you whether any node matches. Asking for Boolean.class converts a node set to "is it non-empty".
Can XPath modify the document? No. XPath only selects. Select the nodes, then change them with DOM methods (article 46), or write an XSLT transformation (article 47).
Is XPath slow on large documents?
Expressions starting with // scan the whole tree, which adds up when you evaluate many expressions. Select records once and evaluate compiled, relative expressions on each. XPath needs a DOM tree in memory, so for huge documents use StAX and extract values while streaming.
API reference
| API | Purpose |
|---|---|
XPathFactory.newInstance().newXPath() | create an XPath evaluator |
XPath.evaluate(expr, item) | string value of the result |
XPath.evaluate(expr, item, XPathConstants.NODESET/NODE/NUMBER/STRING/BOOLEAN) | result as NodeList, Node, Double, String or Boolean |
XPath.evaluateExpression(expr, item, Class<T>) | typed result (Java 9) |
XPath.evaluateExpression(expr, item) | XPathEvaluationResult<?> with type() and value() |
XPathNodes | iterable node set with size() and get(i) |
XPath.compile(expr) | reusable XPathExpression |
XPathExpression.evaluate(item), evaluateExpression(item, Class<T>) | evaluate a compiled expression |
XPath.setXPathVariableResolver(resolver) | supply values for $variables |
XPath.setXPathFunctionResolver(resolver) | supply extension functions |
XPath.setNamespaceContext(context) | map prefixes to namespaces (article 44) |
XPathExpressionException | syntax or evaluation errors |
Summary
- XPath selects nodes with paths:
/for children,//for descendants,@for attributes,..for the parent, and|for unions. - Predicates in brackets filter by position (starting at 1), attribute values, child values and functions.
(//x)[1]differs from//x[1]. - Axes such as
ancestor::andfollowing-sibling::move in other directions. - XPath 1.0 has node sets, strings, numbers and booleans, with functions such as
count,sum,containsandnormalize-space. - Use
evaluateExpressionwith a Java type, iterateXPathNodesdirectly, and compile expressions that you evaluate repeatedly, often relative to a record node. - Pass user input through variables, never by concatenating it into the expression.
Practice Questions
Write an XPath expression for the titles of all English books that cost more than 20.
//book[@lang='en' and price > 20]/title. The comparison converts each price child's text to a number.
What's the difference between //book[1]/title and (//book)[1]/title?
In //book[1], the predicate applies to the book step, so it selects every book that is the first book child of its parent, one per shelf. (//book)[1] first collects all books in document order and then takes the first, giving exactly one book.
How do you get the number of authors as an int with the modern API, and with the older one?
Modern: int n = xpath.evaluateExpression("count(//author)", doc, Integer.class);. Older: int n = ((Number) xpath.evaluate("count(//author)", doc, XPathConstants.NUMBER)).intValue();, since XPath numbers are doubles.
Why is xpath.evaluate("//user[name='" + input + "']/role", doc) dangerous, and what should you write instead?
An attacker can supply input such as ' or '1'='1 and change the logic of the expression, for example to select another user's role. Compile //user[name=$name]/role and supply name through an XPathVariableResolver, so the input is always treated as a string value.
Write an expression for the id of the book that contains an author named Alan Turing, using an axis.
//author[.='Alan Turing']/parent::book/@id, or more simply //author[.='Alan Turing']/../@id. An alternative without axes is //book[author='Alan Turing']/@id.
Previous: Validating XML with XML Schema: Types, Sequences and a Practical Example
Next: XML Namespaces: Prefixes, Default Namespaces and Namespace-Aware Parsing
Related reading
- Validating XML with XML Schema: Types, Sequences and a Practical Example
- Validating XML with Document Type Definitions (DTDs)
- Parsing XML with DOM: DocumentBuilder, Nodes and Secure Parsing
- Introducing XML: Document Structure, Elements and Attributes
- Java Regex Split, Replace and Flags: splitWithDelimiters, replaceAll and Pattern Flags

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.