How to get the last element of a sequence in XPath?
14,777
You can access the last element in XPath using last()
in a predicate.
node.xpath('.//ROOT/TAG[last()]/KEY_NAME')
And use [last()-1]
for the second-to-last position.
Comments
-
Alexander.Iljushkin almost 2 years
In Ruby we can access an array with negative numbers like
array[-1]
to get the last object in the array. How do I do this using XPath?I can't do this:
result = node.xpath('.//ROOT/TAG[-1]/KEY_NAME')
I found a solution here on Stack Overflow, but that is a query that just changes the upper limit to get elements. This could return one last item or last item and prevous.
What if I want to get only the prevous element like
array[-2]
in Ruby? -
Mark Thomas about 11 yearsUse
[last()-1]
for the second-to-last position. -
Alexander.Iljushkin about 11 yearsThank you, guys. You're all awesome :)