tags:

views:

95

answers:

4

I'm writing a Selenium testcase. And here's the xpath expression I use to match all 'Modify' buttons within a data table.

//img[@title='Modify']

My question is, how can I visit the matched node sets by index? I've tried with

//img[@title='Modify'][i]

and

//img[@title='Modify' and position() = i]

But neither works.. I also tried with XPath checker(One firefox extension). There're totally 13 matches found, then I have totally no idea how am I gonna select one of them.. Or does XPath support specified selection of nodes which are not under same parent node?

+2  A: 

There is no i in XPath.

Either you use literal numbers: //img[@title='Modify'][1]

Or you build the expression string dynamically: '//img[@title='Modify']['+i+']' (but keep in mind that dynamic XPath expressions do not work from within XSLT).

Or does XPath support specified selection of nodes which are not under same parent node?

Yes: (//img[@title='Modify'])[13]


This //img[@title='Modify'][i] means "any <img> with a title of 'Modify' and a child element named <i>."

Tomalak
@Tomalak: +1 for explanation about `[i]` predicate's meaning
Alejandro
@Tomalak Thank you very much:) I've got my problem solved..
Kymair Wu
A: 
//img[@title='Modify'][i]

is short for

/descendant-or-self::node()/img[@title='Modify'][i]

hence is returning the i'th node under the same parent node.

You want

/descendant-or-self::img[@title='Modify'][i]
Nick Jones
@Nick Jones: Just `/descendant::img[@title='Modify'][$index]` will work fine. Also note that `[i]` predicate test for existence of `i` child element.
Alejandro
A: 

Ahhhhhhhhhhhhhhhhh... Found the solution after spending 1 whole day..

THANKS A TON Tomalak, your line "Yes: (//img[@title='Modify'])[13]" gave me a sigh of relief..

AUTsol
+4  A: 

This is a FAQ:

//someName[3]

means: all someName elements in the document, that are the third child of their parent -- there may be many such elements.

What you want is exactly the 3rd someName element:

(//someName)[3]

Explanation: the [] has a higher precedence (priority) than //. Remember always to put expressions of the type //someName in brackets when you need to specify the Nth node of their selected node-list.

Dimitre Novatchev
@Dimitre: +1 for precedence explanation.
Alejandro
@Dimitre Thanks so much! Sorry I totally forgot the precedence things.. I just tried and it works!
Kymair Wu
@Kymair-Wu: I am glad this answer was useful to you. Here at SO the way of expressing gratitude is by accepting an answer (hint: click on the check-mark next to the answer). :)
Dimitre Novatchev