views:

48

answers:

3

Hi everyone,

I'm trying to figure out a way of finding the last node that matches a given xpath using last() function. The problem is that the last element of path also has a constraint specified.

"//div[@id='someId']/ul/li/div[@class='class1 class2 ']/span[@class='someType2 ']"

if I use

"//div[@id='someId']/ul/li/div[@class='class1 class2 ']/span[@class='someType2 ']' and last()]"

it still matches multiple nodes. Maybe one of the reasons is that the last div tag in the path contains 2 span elements. please help me select the last node which matches the above path.

Thanks and Regards,
Vamyip

+1  A: 

If your xml is xhtml, why don't use CSS selectors ? If I'm not mistaken, the selectors should be

#someId > ul > li > div.class1.class2 > span.someType2

#someId > ul > li > div.class1.class2 > span.someType2:last

I was using xpath on html pages too, but when CSS selectors became widespread I found that they are more supported across browsers than xpath.

Riccardo Galli
The 1st selector you specified is working correctly and matches the 1st element. But, the keyword 'last' seems to break the selector. Is there any alternate syntax for this keyword? Thanks
vamyip
I tested it and it works. What do you use to run the selector query, and in what platform / browser ?
Riccardo Galli
I'm using it in selenium-rc scripts. You can try it by adding the selenium IDE plugin for Firefox. You'll need to refer a small tutorial before using it. http://seleniumhq.org Anyways thanks for your help. Really appreciate it.
vamyip
+1  A: 

Use:

(//div[@id='someId']/ul/li/div[@class='class1 class2 ']
                                  /span[@class='someType2 '])
                                          [last()]

Do note: the brackets surrounding the expression starting with //. This is a FAQ. [] binds stronger than // and this is why brackets are necessary to indicate different precedence.

Dimitre Novatchev
Thanks for your reply. I 'm currently using Xpath for selenium and the round brackets break the Xpath for selenium. Otherwise your answer is perfect, it works perfectly fine in xpath viewer as well as fire xPath. Thanks again
vamyip
@vamyip: Sorry. In this case your question is not a XPath question and must be classified as "selenium-xpath".
Dimitre Novatchev