How to test an XPath expression
- Paste XML or open a file. If it is not well-formed, the error and its line appear instead of results; the XML validator explains them.
- Type the expression in the box above the results. Matches update as you type.
- Each match shows its path and the node: elements as XML, attributes and text as their value. Expressions such as
count(//node)show a single number, string or boolean.
Examples
<cluster name="eu-west">
<node id="n1" role="primary">
<host>db1.internal</host>
<cpu>8</cpu>
</node>
<node id="n2" role="replica">
<host>db2.internal</host>
<cpu>4</cpu>
</node>
<node id="n3" role="replica">
<host>db3.internal</host>
<cpu>16</cpu>
</node>
</cluster>
| Expression | Result |
|---|---|
//node[@role='replica']/host |
2 matches: the <host> of n2 and n3 |
//node[cpu > 6]/@id |
n1, n3 |
count(//node) |
3 |
sum(//cpu) |
28 |
string(/cluster/@name) |
eu-west |
//host[1] |
3 matches |
(//host)[1] |
1 match: db1.internal |
[1] applies to the step right before it, so //host[1] means every host that is first in its parent: all three. Parentheses take the first match in the whole document.
Default namespaces return nothing
A Maven POM declares a default namespace on its root:
<project xmlns="http://maven.apache.org/POM/4.0.0">
<artifactId>billing</artifactId>
<version>2.3.0</version>
</project>
/project/version matches nothing: in XPath 1.0 an unprefixed name only matches elements in no namespace. Use the local name: /*[local-name()='project']/*[local-name()='version']. Prefixes declared on the root element work as written, such as //soap:Body.
The XPath tester runs XPath 1.0
It uses document.evaluate, the XPath 1.0 engine in every browser, so expressions behave as they do in front-end code. XPath 2.0 functions such as ends-with(), lower-case() and matches() return an XPath error. Their 1.0 stand-ins:
ends-with(., '.internal'):substring(., string-length(.) - string-length('.internal') + 1) = '.internal'lower-case(@role):translate(@role, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')matches(): no regular expressions in 1.0; combinecontains()andstarts-with().
The Tree in the XML formatter copies the XPath of any node. For JSON, use the JSONPath tester.