Xpath select n-th node
I have such XML
<div class="yay"> <div class="foo"></div> <div class="foo"></div> <div class="bar"></div> <div class="foo"></div> <div class="bar"></div> <div class="foo"></div> </div>
Is there a way to select the nth div where the class is "foo"?
I would select all foos using //div[@class="yay"/div[@class="foo"]
If I want to choose foo # 3, how to do it? Sort of:
//div[@class="yay"/div[@class="foo"][3]
?
This is one of the most frequently asked questions in XPath .
Using
(//div[@class="yay"]/div[@class="foo"])[3]
Explanation
The XPath pseudo-operator //
has a lower priority (priority) than the []
operator.
Thus
//div[@class="yay"]/div[@class="foo"][3]
means
Select each div
whose class
attribute is set to "foo"
and that ( div
) is the third such child of its parent div
.
If there are several parent div
elements that have three or more such child elements, then all 3 children are selected.
As with many expression languages, the way to override the built-in priority is to use parentheses .