15

I'm new to xpath and I understand how to get a range of values in xpath:

/bookstore/book[position()>=2 and position()<=10]

but in my case, I need to get above 2 and one less then the total(so if there's 10 then I need 9, or if there's 5, I need up to the 4th spot). I'm applying my code to different pages and the number of entries is not always the same.

In python, I could do something like book[2:-2], but I'm unsure if I can do this within xpath.

2
  • 1
    /bookstore/book[position()>=2 and position() <= (last() - 1)] Commented Apr 25, 2014 at 1:19
  • @helderdarocha WORKED!!! Can you do me a favour and put it as a answer so I can accept it? Thank you so much!
    – Lostsoul
    Commented Apr 25, 2014 at 1:22

2 Answers 2

20

You can use last() which represents the last item in the context:

/bookstore/book[position()>=2 and position() <= (last() - 1)]
3
  • thanks, tried it again and it worked. Thank you so much.
    – Lostsoul
    Commented Apr 25, 2014 at 1:27
  • unable to fetch using this method Commented Dec 17, 2020 at 16:31
  • 1
    Should it be /bookstore/book[position() = (last() - 1)] ? Because this accepted answer does include every node between index 2 and N - 1, and not just the second last one.
    – FonzTech
    Commented Jan 12, 2021 at 13:15
6

In my case this was working for me to get last but one element

/bookstore/book[position() = (last() - 1)]

Not the answer you're looking for? Browse other questions tagged or ask your own question.