Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

xml

xpath

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?

like image 728
tao4yu Avatar asked Oct 16 '25 13:10

tao4yu


1 Answers

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]
like image 136
har07 Avatar answered Oct 19 '25 09:10

har07