PHP XPath 选择最后一个匹配元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5537129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:45:10  来源:igfitidea点击:

PHP XPath selecting last matching element

phpxpath

提问by deab

Possible Duplicates:
PHP SimpleXML. How to get the last item?
XSLT Select all nodes containing a specific substring

可能的重复项:
PHP SimpleXML。如何获得最后一个物品?
XSLT 选择包含特定子字符串的所有节点

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.

我需要找到具有“myClass”类的最后一个 span 元素的内容。我尝试了各种组合,但找不到答案。

//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.

这将返回具有“myClass”类的所有元素,我猜这是因为每个找到的元素都是处理时的最后一个元素 - 但我只需要实际的最后一个匹配元素。

回答by VolkerK

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']视为当前集合的处理器,然后将谓词 position()=last() 应用于该集合。

(//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;
}

回答by Michael Kay

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:

您使用的表达式的意思是“选择每个 span 元素,前提是 (a) 它具有@class='myprice',并且 (b) 它是其父级的最后一个子级。有两个错误:

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

(1) 需要[position()=last()]通过@class过滤后应用过滤器,而不是应用到所有span元素

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

(2) 形式的表达//span[last()]意味着/descendant-or-self::*/(child::span[last()])选择每个元素的最后一个子跨度。您需要使用括号来更改优先级: (//span)[last()].

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

所以表达式变成(//span[@class='myPrice'])[last()]了 VolkerK 给出的。