Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

java - Why is XPath last() function not working as I expect?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  1. 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 because [] has a higher precedence than //.

  2. 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 because () is used to override the default precedence.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...