Some title

don't select me

select me 1

sel...">

XPATH - node range selection

I have the following code:

<div id="mydiv">
    <h1>Some title</h1>
    <p>don't select me</p>
    <p>select me 1</p>
    <p>select me 2</p>
    <p>select me 3</p>
    <p>don't select me</p>
</div>

I need to select p [2] through p [4].

Tried this code and it did not work:

'.//*[@id="mydiv"]/p[preceding-sibling::p[4] and following-sibling::p[2]]'
+3
source share
3 answers

You can try:

'//*[@id='mydiv']/p[position()>1 and position()<5]'


Or your source code can be changed to:

'//*[@id="mydiv"]/p[preceding-sibling::p and following-sibling::p]'


So that all pwith the previous and next nodes pare selected (ie p [2] - p [4]).

+5
source

Perhaps you need to use this if the maximum number "p" is greater than 5:

//p[(position() idiv 2) eq 1] --- to select ODD nodes (based on item number)

//p[(position() idiv 2) eq 0] --- to select EVEN nodes (based on item number)

0
source

XPATH can also be written in the following format: -

//p[position()>1 and position()<5]

OR

//p[position()>=2 and position()<=4]

Result:

select me 1
select me 2
select me 3
0
source

All Articles