XPath Predicates

Nesting predicates

//section[.//h1[@id='hi']]

This returns <section> if it has an <h1> descendant with id='hi'.

Chaining order

a[1][@href='/']
a[@href='/'][1]

Order is significant, these two are different.

Indexing

//a[1]                # first <a>
//a[last()]           # last <a>
//ol/li[2]            # second <li>
//ol/li[position()=2] # same as above
//ol/li[position()>1] #:not(:first-child)

Use [] with a number, or last() or position().

Using nodes

# Use them inside functions
//ul[count(li) > 2]
//ul[count(li[@class='hide']) > 0]
# Returns `<ul>` that has a `<li>` child
//ul[li]

You can use nodes inside predicates.

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)]

Predicates

//div[true()]
//div[@class="head"]
//div[@class="head"][@id="top"]

Restricts a nodeset only if some condition is true. They can be chained.

Comments