tao4yu
tao4yu

Reputation: 336

XPath: How to select a range of nodes in the node set?

I want to select a range of nodes in a node set. I tried, but I cannot get the result.

example.xml:

<div>
    <p class="p1">a</p>
    <p class="p2">b</p>
    <p class="p3">c</p>
</div>
<div>
    <p class="p1">aa</p>
    <p class="p2">bb</p>
    <p class="p3">cc</p>
</div>
<div>
    <p class="p1">aaa</p>
    <p class="p2">bbb</p>
    <p class="p3">ccc</p>
</div>
<div>
    <p class="p1">aaaa</p>
    <p class="p2">bbbb</p>
    <p class="p3">cccc</p>
</div>

I want to get the second to third pnodes( have class="p1"), I wrote the xpath:
"//div/p[@class='p1'][position()>=2 and position()<4]", But it failed.I guess that if every time "//div/p[@class='p1']" get one node, and its position is 0, so I can not get a node which position>=2 and position<4, so the result is none.But How can I write the xpath?

Upvotes: 4

Views: 3211

Answers (1)

har07
har07

Reputation: 89305

Your guess is about correct.

The ([]) has a higher precedence (priority) than (// and /). [For Reference]

So you need to wrap XPath before position filter within brackets as follow :

(//div/p[@class='p1'])[position()>=2 and position()<4]

Upvotes: 9

Related Questions