How to get the last element of a sequence in XPath?

Alexander.Iljushkin picture Alexander.Iljushkin · Apr 22, 2013 · Viewed 13.6k times · Source

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?

Answer

Jens Erat picture Jens Erat · Apr 22, 2013

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.