Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath select n-th node

Tags:

xpath

I have a XML like this

<div class="yay">
 <div class="foo"></div> 
 <div class="foo"></div>
 <div class="bar"></div>
 <div class="foo"></div>
 <div class="bar"></div>
 <div class="foo"></div>
</div>

Is there a way to select the n-nth div where class is "foo"?

I'd select all foos with //div[@class="yay"/div[@class="foo"]

If I want to select foo #3 how do I do that? Something like:

//div[@class="yay"/div[@class="foo"][3] ?

like image 414
Jay Avatar asked May 16 '12 00:05

Jay


People also ask

How do you find the nth element using XPath?

In case we need to identify nth element we can achieve this by the ways listed below. position() method in xpath. Suppose we have two edit boxes in a page with similar xpath and we want to identify the first element, then we need to add the position()=1.

How do you select the second element with the same XPath?

For example if both text fields have //input[@id='something'] then you can edit the first field xpath as (//input[@id='something'])[1] and the second field's xpath as (//input[@id='something'])[2] in object repository.

How do I select the first child in XPath?

The key part of this XPath is *[1] , which will select the node value of the first child of Department . If you need the name of the node, then you will want to use this... Save this answer.

What is the meaning of '/' in XPath?

0 votes. Single Slash “/” – Single slash is used to create Xpath with absolute path i.e. the xpath would be created to start selection from the document node/start node.


1 Answers

This is one of the most FAQ in XPath.

Use:

(//div[@class="yay"]/div[@class="foo"])[3]

Explanation:

The XPath pseudo-operator // has lower precedence (priority) that the [] operator.

Thus

//div[@class="yay"]/div[@class="foo"][3]

means:

Select every div whose class attribute has the value "foo" and that (the div) is the third such div child of its parent.

If there are more than one parent div elements that have three or more such children, then all of the 3rd children are selected.

As with many expression languages, the way to override built-in priority is to use parenthesis.

like image 62
Dimitre Novatchev Avatar answered Oct 04 '22 19:10

Dimitre Novatchev