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.

Share:
14,777
Alexander.Iljushkin
Author by

Alexander.Iljushkin

Hello, friend. I'm pleased to meet you.

Updated on July 04, 2022

Comments

  • Alexander.Iljushkin
    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
    Mark Thomas about 11 years
    Use [last()-1] for the second-to-last position.
  • Alexander.Iljushkin
    Alexander.Iljushkin about 11 years
    Thank you, guys. You're all awesome :)