Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPATH - select range of nodes

Tags:

php

xpath

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]]'
like image 976
RhymeGuy Avatar asked Apr 23 '12 22:04

RhymeGuy


2 Answers

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]).

like image 54
Aleh Douhi Avatar answered Nov 15 '22 05:11

Aleh Douhi


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
like image 21
Siva Charan Avatar answered Nov 15 '22 03:11

Siva Charan