tags:

views:

211

answers:

3

How can I ignore first element and get rest of the elements?

<ul>
  <li><a href="#">some link</a></li>
  <li><a href="#">some link 2</a></li>
  <li><a href="#">link i want to find</a></li>
</ul>

Thanks

A: 

Assuming you want the anchor:

$first = true;

foreach($xml->xpath('//a') as $node) {
    if (!$first) {
        // Do your thing
    } else {
        $first = false;
    }
}
Danten
I would like to get it by using xpath only.
priyank
+4  A: 

if you want to ignore the "first" element only then:

//li[position()>1]
or
(//a)[position()>1] 

if you want the last only (like your example seems to suggest):

//li[last()]
or
(//a)[last()]
t00ny
Remember that indexes in XPath are 1-based, not 0-based. So the expression `a[position()>1]` returns all `a` elements except the first one.
isme
position() returns the position of the context element. In the XPATH provided, the position of each `a` would equal 1 AND last() and return each of the `a` elements, not skipping the first.
Mads Hansen
In order to get `position()` to evaluate as expected, you need to wrap the selection of elements in parentheses to group them in a node-set and *then* apply the predicate filter on position (i.e. (`//a)[position()>1]` and `(//a)[last()]` )
Mads Hansen
@isme... yes i know it's 1 based, but i was puzzled by the question because he says he wants to ignore the first element, but the example suggests he'd only want the last one
t00ny
-1 This answer is wrong in the context of the question. There is no `//a[position()>1]` in the example, and `//a[last()]` has three matches. Did you test your XPath before posting it?
Tomalak
@Tomalak you're right! i did it wrong, i should be using "li" instead if "a" i'll to the adjustment... sorry about that
t00ny
@Mads Hansen: you're also right i adjusted my response according to your comments thanks!
t00ny
@t00ny: Downvote revoked.
Tomalak
+1  A: 

You can use position() to skip over the "first" one, but depending on which element you are interested in and what the context is, you may need a slight variation on your XPATH.

For instance, if you wanted to address all of the li elements and get all except the first, you could use:

//li[position()>1]

and it would work as expected, returning all of the li elements except for the first.

However, if you wanted to address all of the a elements you need to modify the XPATH slightly. In the context of the expression //a[position()>1] each one of the a elements will have a position() of 1 and last() will evaluate to true. So, it would always return every a and would not skip over the first one.

You need to wrap the expression that selects the a in parenthesis to group them in a node-set, then apply the predicate filter on position.

(//a)[position()>1]

Alternatively, you could also use an expression like this:

//a[preceding::a]

That will find all a elements except the first one (since there is no a preceding the first one).

Mads Hansen