【问题标题】:Obtaining min/max values of an element with xpath使用 xpath 获取元素的最小/最大值
【发布时间】:2019-09-17 18:43:39
【问题描述】:

我有一个像这样的 xml 表:

<f:device-list>
    <f:device name="Voltage Converter" quantity="2" serial_number="20011">
        <f:weight units="pounds">3.00</f:weight>
    </f:device>
    <f:device name="24-port switch" quantity="2" serial_number="24PORTSW-004">
        <f:weight units="pounds">3.34</f:weight>
    </f:device>
</f:device-list>

我正在使用 simplexml 和 xpath 获取设备的重量,如下所示:

foreach($xml->xpath('//f:weight[@units="pounds"]') as $weightLB) {
        echo $weightLB;
        echo "</br>";
}

我试图弄清楚如何获得权重元素的最小值和最大值。我已经查看了许多有关 xpath 的解决方案,但大多数都涵盖了属性值,并且不适用于像这样格式化的工作表。任何帮助将不胜感激!

【问题讨论】:

  • 为什么不使用max($weightLB)min($weightLB)
  • 是一个简单的xml对象,抛出错误"When only one parameter is given, it must be an array"
  • 如果您想要纯 XPath 版本 - 请阅读 stackoverflow.com/a/1129929/1213708。对于这种情况,Max - //f:weight[@units="pounds"][. &gt; //f:weight[@units="pounds"]]
  • @NigelRen 那个答案有一些问题。在stackoverflow.com/a/57981655/11102282下方查看我的解决方案@

标签: php xml xpath


【解决方案1】:

您可以将所有值映射到一个数组,然后使用maxmin 函数:

<?php

$xml = <<<XML
<?xml version='1.0'?>
    <device-list>
    <device name="Voltage Converter" quantity="2" serial_number="20011">
        <weight units="pounds">3.00</weight>
    </device>
    <device name="24-port switch" quantity="2" serial_number="24PORTSW-004">
        <weight units="pounds">3.34</weight>
    </device>
</device-list>
XML;

$simpleXml = simplexml_load_string($xml);

$weights = array_map(function($elem) {
    return $elem->__toString();
}, $simpleXml->xpath('//weight[@units="pounds"]'));

echo "Min: " .min($weights) . "<br/>";
echo "Max: " .max($weights);

输出:

分钟:3.00

最大值:3.34

【讨论】:

  • 太棒了!谢谢!
  • 您可以将$elem 转换为浮点数而不是字符串。
【解决方案2】:

我添加了这个纯 XPath 1.0 答案,因为 cmets 中的链接在这种情况下是错误的。最大值的一般成语:

($node-set[not(. < $node-set)])[1]

意思:

从带有编号的节点集中选择第一个(按文档顺序) 值不小于节点集中的任何其他值。

供您输入(现在格式正确):

<f:device-list xmlns:f="dummy">  
  <f:device name="Voltage Converter" quantity="2" serial_number="20011"> 
    <f:weight units="pounds">3.00</f:weight> 
  </f:device>  
  <f:device name="24-port switch" quantity="2" serial_number="24PORTSW-004"> 
    <f:weight units="pounds">3.34</f:weight> 
  </f:device> 
</f:device-list>

此 XPath 1.0 表达式(f 前缀绑定到 dummy 命名空间 URI):

(//f:weight[@units='pounds'][not(. < //f:weight[@units='pounds'])])[1]

它选择:

<f:weight xmlns:f="dummy" units="pounds">3.34</f:weight>

签到http://www.xpathtester.com/xpath/1969ef047d90f2efbb0dcc1d1e131428

注意:位置谓词(如[1] 缩写形式)对位置步轴起作用,这意味着如果集合中的所有节点都是第一个子节点,那么您需要括号来获得第一个按文档顺序。

【讨论】:

  • 对不起 - 我不确定你在哪里说链接的答案对这种情况不起作用。你似乎把 。
  • @NigelRen 对位置谓词也有适当的解释。根据重复的最大值here 检查 OP 输入样本的链接答案
猜你喜欢
  • 2017-05-14
  • 2018-07-07
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多