How to select the second element with same attribute ID in an XPATH?

11,053

Two solutions have been proposed so far, but none of them selects anything from the HTML snippet you show in the question. When simply wrapping it in a root element:

<root>
 <div>
    <div class="content">test1</div>
 </div>
 <div>
    <div class="content">test2</div>
 </div>
 <div>
    <div class="content">test3</div>
 </div>
</root>

Both //div[@class='content'][2] and //div[2][@class='content'] select nothing from that document. They both assume that the second predicate (between [ and ]) is applied to an intermediate result sequence, but the second predicate is also applied to the nodes of the initial document tree. To select a subset of an "intermediate" result, use parentheses around the first part:

(//div[@class='content'])[2]

and the single result will be

<div class="content">test2</div>

More details

//div[@class='content'][2] means:

Select all elements called div from anywhere in the document, but only the ones that have a class attribute whose value is equal to "content". Of those selected nodes, only keep those which are the second div[@class = 'content'] element of their parent.

So, this expression would only select a result from the following document:

<root>
 <div>
    <div class="content">test1</div>
 </div>
 <div>
    <div class="content">test2</div>
    <div class="other">other</div>
    <div class="content">MATCH</div>
 </div>
 <div>
    <div class="content">test3</div>
 </div>
</root>

//div[2][@class='content'] means:

Select all elements called div from anywhere in the document, but only the ones that are the second child of their parent. Of those selected nodes, only keep those which have a class attribute whose value is equal to "content".

Only producing a match given a document like

<root>
 <div>
    <div class="content">test1</div>
 </div>
 <div>
    <div class="other">other</div>
    <div class="content">MATCH</div>
 </div>
 <div>
    <div class="content">test3</div>
 </div>
</root>
Share:
11,053
kndarp
Author by

kndarp

Learning never stops

Updated on June 11, 2022

Comments

  • kndarp
    kndarp almost 2 years

    Imagine an HTML snippet as follows:

    <div>
        <div class="content">test1</div>
    </div>
    <div>
        <div class="content">test2</div>
    </div>
    <div>
        <div class="content">test3</div>
    </div>
    

    and the xpath I'm using is //div[@class='content']

    Now, I want to refer to the Second div element. What should I add to my xpath? TIA.