Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 517
Alexander.Iljushkin Avatar asked Apr 22 '13 07:04

Alexander.Iljushkin


1 Answers

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.

like image 55
Jens Erat Avatar answered Oct 05 '22 12:10

Jens Erat