LoveLovelyJava one LoveLovelyJava one - 7 months ago 12
Java Question

last() function doesn't always bring me the last element

I am using Java and Selenium to write a test. I need to get the last element inside another element, so I used

last()
function, but the problem is that it doesn't always bring me the last one when I apply :

//a//b[last()]


to

<a>
<l>
<b>asas</b>
</l>
<b>as</b>
</a>


to get
<b>as</b>
,it brings me:

<b>asas</b>

<b>as</b>


but when I apply it to:

<a>
<b>asas</b>
<b>as</b>
</a>


it brings me:

<b>as</b>

Answer

This is a common source of XPath confusion. First the straightforward parts:

  • //a selects all a elements in the document.
  • //a//b selects all b elements in the document that are descendants of a elements.

Normal stuff so far. Next is the tricky part:

  • To select the last b elements among siblings (beneath a elements):

    //a//b[last()]
    

    Here, the filtering is a part of the b selection criteria.

  • To select the last b element in the document (beneath a elements):

    (//a//b)[last()]
    

    Here, the last() is an index on the list of all selected b elements.