RhymeGuy
RhymeGuy

Reputation: 2112

XPATH - select range of nodes

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 with this code and it didn't work:

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

Upvotes: 5

Views: 5802

Answers (3)

Aleh Douhi
Aleh Douhi

Reputation: 1988

You can try:

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


Or, your initial code can be changed to:

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


So that all of the p with preceding and following p nodes will be selected (i.e. p[2] through p[4]).

Upvotes: 10

Siva Charan
Siva Charan

Reputation: 18064

XPATH can be written in below format too:-

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

OR

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

Result:

select me 1
select me 2
select me 3

Upvotes: 1

Cylian
Cylian

Reputation: 11182

Perhaps you need to use this, if max number of «p» greater than 5:

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

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

Upvotes: 0

Related Questions