Reputation: 193
I have an XPath that returns two items. I want to modify it so that it returns only the second, or the last if there are more than 2.
//a[@rel='next']
I tried
//a[@rel='next'][2]
but that doesn't return anything at all. How can I rewrite the xpath so I get only the 2nd link?
Upvotes: 0
Views: 389
Reputation: 193
Found the answer in XPATH : finding an attribute node (and only one)
In my case the right XPath would be
(//a[@rel='next'])[last()]
EDIT (by Tomalak) - Explanation:
This selects all a[@rel='next']
nodes, and takes the last of the entire set:
(//a[@rel='next'])[last()]
This selects all a[@rel='next']
nodes that are the respective last a[@rel='next']
of the parent context each of them is in:
//a[@rel='next'][last()] equivalent: //a[@rel='next' and position()=last()]
This selects all a[@rel='next']
nodes that are the second a[@rel='next']
of the parent context each of them is in (in your case, each parent context had only one a[@rel='next']
, that's why you did not get anything back):
//a[@rel='next'][2] equivalent: //a[@rel='next' and position()=2]
For the sake of completeness: This selects all a
nodes that are the last of the parent context each of them is in, and of them only those that have @rel='next'
(XPath predicates are applied from left to right!):
//a[last()][@rel='next'] NOT equiv!: //a[position()=last() and @rel='next']
Upvotes: 2