Ian Wood
Ian Wood

Reputation: 6573

xpath - get first 10 items of selected set

xml again..

I want to select a sub set of nodes ( for pagination purposes ) from a set.

$nodes = $xml->query(//parent
                        /child[sex = 'male' 
                               and position() >= 10 
                               and position() < 21]);

If I'm not mistaken that would only select male children who are the 10th to 20th child.

what I need is to select the first 10-20 (or 30-40) males in the set...

sure I'm being a noob and have done this before but its friday...

ta peeps

Upvotes: 13

Views: 25321

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243519

I want to select a sub set of nodes ( for pagination purposes ) from a set.

$nodes = $xml->query(//parent
                         /child[sex = 'male'
                                 and position() >= 10
                                 and position() < 21]); 

If I'm not mistaken that would only select male children who are the 10th to 20th child.

what I need is to select the first 10-20 (or 30-40) males in the set...

You are mistaken...

//parent/child
           [sex = 'male'
          and 
           position() >= 10
          and 
           position() < 21
           ] 

Selects all child elements (of any parent element in the XML document) that have a sex child with sting value "male" and that are one of the 10th to 20th child children of their parent.

There could be only a few, or even none such elements.

What you want is:

  1. Selects all child elements (of any parent element in the XML document) that have a sex child with sting value "male"

  2. From the ones selected in step 1 above select only those in position 10 to 20

So, for step 1:

//parent/child[sex = 'male']

and adding step 2:

//parent/child[sex = 'male']
                [position() >= 10
               and 
                not(position() > 20
                ]

Upvotes: 6

Chris Cameron-Mills
Chris Cameron-Mills

Reputation: 4657

Have the position condition operate on the result nodeset of your initial condition:

//parent/child[sex='male'][position() >= 10 and position() < 21]

Upvotes: 32

Related Questions