开发者

PHP XPath selecting last matching element [duplicate]

This question already has answers here: 开发者_Python百科 Closed 11 years ago.

Possible Duplicates:

PHP SimpleXML. How to get the last item?

XSLT Select all nodes containing a specific substring

I need to find the contents of the last span element with a class of 'myClass'. I've tried various combinations but can't find the answer.

//span[@class='myPrice' and position()=last()]

This returns all the elements with class 'myClass', I'm guessing this is because each found element is the last at the time of processing - but I just need the actual last matching element.


You have to mark for the processor that you want to treat //span[@class='myPrice'] as the current set and then apply the predicate position()=last() to that set.

(//span[@class='myPrice'])[last()]

e.g.

<?php
$doc = getDoc();
$xpath = new DOMXPath($doc);
foreach( $xpath->query("(//span[@class='myPrice'])[last()]") as $n ) {
  echo $n->nodeValue, "\n";
}


function getDoc() {
  $doc = new DOMDOcument;
  $doc->loadxml( <<< eox
<foo>
  <span class="myPrice">1</span>
  <span class="yourPrice">0</span>
  <bar>
    <span class="myPrice">4</span>
    <span class="yourPrice">99</span>
  </bar>
  <bar>
    <span class="myPrice">9</span>
  </bar>
</foo>
eox
  );
  return $doc;
}


The expression you used means "select every span element provided that (a) it has @class='myprice', and (b) it is the last child of its parent. There are two errors:

(1) you need to apply the filter [position()=last()] after filtering by @class, rather than applying it to all span elements

(2) an expression of the form //span[last()] means /descendant-or-self::*/(child::span[last()]) which selects the last child span of every element. You need to use parentheses to change the precedence: (//span)[last()].

So the expression becomes (//span[@class='myPrice'])[last()] as given by VolkerK.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜