XPath (XML Path Language) is an expression language for selecting nodes from an XML or HTML document.
Testing
XPath Testbed
Test and experiment with XPath expressions interactively:
- XPath Testbed (whitebeam.org)
Browser Console
$x("//div")
Available directly inside Chrome, Edge, and Firefox DevTools consoles.
Selectors
Descendant Selectors
| CSS | XPath | Reference |
|---|---|---|
h1 |
//h1 |
? |
div p |
//div//p |
? |
ul > li |
//ul/li |
? |
ul > li > a |
//ul/li/a |
|
div > * |
//div/* |
|
:root |
/ |
? |
:root > body |
/body |
Attribute Selectors
| CSS | XPath | Reference |
|---|---|---|
#id |
//*[@id="id"] |
? |
.class |
//*[@class="class"] |
? |
input[type="submit"] |
//input[@type="submit"] |
|
a#abc[for="xyz"] |
//a[@id="abc"][@for="xyz"] |
? |
a[rel] |
//a[@rel] |
|
a[href^='/'] |
//a[starts-with(@href, '/')] |
? |
a[href$='pdf'] |
//a[ends-with(@href, '.pdf')] |
|
a[href*='://'] |
//a[contains(@href, '://')] |
|
a[rel~='help'] |
//a[contains(@rel, 'help')] |
? |
Order & Index Selectors
| CSS | XPath | Reference |
|---|---|---|
ul > li:first-of-type |
//ul/li[1] |
? |
ul > li:nth-of-type(2) |
//ul/li[2] |
|
ul > li:last-of-type |
//ul/li[last()] |
|
li#id:first-of-type |
//li[1][@id="id"] |
? |
a:first-child |
//*[1][name()="a"] |
|
a:last-child |
//*[last()][name()="a"] |
Sibling Elements
| CSS | XPath | Reference |
|---|---|---|
h1 ~ ul |
//h1/following-sibling::ul |
? |
h1 + ul |
//h1/following-sibling::ul[1] |
|
h1 ~ #id |
//h1/following-sibling::*[@id="id"] |
jQuery Equivalents
| jQuery | XPath | Reference |
|---|---|---|
$('ul > li').parent() |
//ul/li/.. |
? |
$('li').closest('section') |
//li/ancestor-or-self::section |
|
$('a').attr('href') |
//a/@href |
? |
$('span').text() |
//span/text() |
Conditionals & Logic
| Condition | XPath | Reference |
|---|---|---|
h1:not([id]) |
//h1[not(@id)] |
? |
| Text exact match | //button[text()="Submit"] |
? |
| Text substring match | //button[contains(text(),"Go")] |
|
| Arithmetic condition | //product[@price > 2.50] |
|
| Has any child element | //ul[*] |
|
| Has specific child element | //ul[li] |
|
| "OR" logic | //a[@name or @href] |
? |
| Union (merge sets) | //a | //div |
? |
Class Check
//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]
XPath 1.0 lacks a whitespace-delimited token matching operator; this standard workaround matches whole classes safely.
Expressions
Steps and Axes
Anatomy of an expression:
// |
ul |
/ |
a[@id='link'] |
|---|---|---|---|
| Axis | Step | Axis | Step |
Prefixes
| Prefix | Example | Meaning |
|---|---|---|
// |
//hr[@class='edge'] |
Anywhere in the document |
./ |
./a |
Relative to the current context |
/ |
/html/body/div |
From root element |
Expressions can start with any of these prefixes.
Axes
| Axis | Example | Meaning |
|---|---|---|
/ |
//ul/li/a |
Immediate child node |
// |
//*[@id="list"]//a |
Any descendant node |
Steps are separated by /. Use // to match any descendant level.
Steps
//div
//div[@name='box']
//*[@id='link']
Steps can contain tag names and predicates ([...]). Both are optional. Steps can also target node values:
//a/text() #=> "Go home"
//a/@href #=> "index.html"
//a/* #=> All children of <a>
Predicates
Predicates
//div[true()]
//div[@class="head"]
//div[@class="head"][@id="top"]
Filter down node sets when conditions match. Predicates can be chained consecutively.
Operators
# Comparison
//a[@id = "xyz"]
//a[@id != "xyz"]
//a[@price > 25]
# Logic (and/or)
//div[@id="head" and position()=2]
//div[(x and y) or not(z)]
Using Nodes in Predicates
# Inside functions
//ul[count(li) > 2]
//ul[count(li[@class='hide']) > 0]
# Returns <ul> only if it has an <li> child
//ul[li]
Indexing
//a[1] # First <a> (1-based index)
//a[last()] # Last <a>
//ol/li[2] # Second <li>
//ol/li[position()=2] # Same as above
//ol/li[position()>1] # All except the first
Chained Order
a[1][@href='/']
a[@href='/'][1]
Order matters: the first takes item 1 and checks its href; the second filters by href first and picks the first match.
Nested Predicates
//section[.//h1[@id='hi']]
Returns <section> elements containing an <h1> descendant with id='hi'.
Functions
Node Functions
name() # Starts with: //[starts-with(name(), 'h')]
text() # Exact match: //button[text()="Submit"]
# Value: //button/text()
lang(str)
namespace-uri()
count() # //table[count(tr)=1]
position() # //ol/li[position()=2]
Boolean Functions
not(expr) # //button[not(starts-with(text(),"Submit"))]
String Functions
contains() # //span[contains(@class,"head")]
starts-with() # //span[starts-with(@class,"head")]
ends-with() # //span[ends-with(@class,"head")]
concat(x, y)
substring(str, start, len)
substring-before("01/02", "/") #=> "01"
substring-after("01/02", "/") #=> "02"
translate()
normalize-space()
string-length()
Type Conversion
string()
number()
boolean()
Axes
Using Axes
//ul/li # ul > li
//ul/child::li # ul > li (explicit child axis)
//ul/following-sibling::li # ul ~ li
//ul/descendant-or-self::li # ul li
//ul/ancestor-or-self::li # $('ul').closest('li')
Axis syntax:
// |
ul |
/child:: |
li |
|---|---|---|---|
| Axis | Step | Axis | Step |
Other Axes
| Axis | Shorthand | Description |
|---|---|---|
ancestor |
Ancestor elements | |
ancestor-or-self |
Context node and its ancestors | |
attribute |
@ |
@href is shorthand for attribute::href |
child |
Default axis: div is child::div |
|
descendant |
Descendants | |
descendant-or-self |
// |
// is shorthand for /descendant-or-self::node()/ |
namespace |
Namespace nodes | |
self |
. |
. is shorthand for self::node() |
parent |
.. |
.. is shorthand for parent::node() |
following |
Everything after closing tag | |
following-sibling |
Sibling nodes after current | |
preceding |
Everything before opening tag | |
preceding-sibling |
Sibling nodes before current |
Unions
//a | //span
Use | to merge two or more node sets together into a union.
Examples
Common Query Patterns
//* # All elements
count(//*) # Count all elements
(//h1)[1]/text() # Text of the very first h1 heading in document
//li[span] # Find <li> containing a <span> child
//ul/li/.. # Navigate back to parent <ul>
Finding Parent Elements
//section[h1[@id='section-name']]
Finds a <section> containing a direct child h1#section-name.
//section[.//h1[@id='section-name']]
Finds a <section> containing any descendant h1#section-name.