使用 xpath 获取元素的最小/最大值

我有一个像这样的 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 的解决方案,但大多数都涵盖了属性值,并且不适用于像这样格式化的工作表。任何帮助,将不胜感激!


慕无忌1623718
浏览 445回答 2
2回答

人到中年有点甜

您可以将所有值映射到一个数组,然后使用max和min函数:<?php$xml = <<<XML<?xml version='1.0'?>&nbsp; &nbsp; <device-list>&nbsp; &nbsp; <device name="Voltage Converter" quantity="2" serial_number="20011">&nbsp; &nbsp; &nbsp; &nbsp; <weight units="pounds">3.00</weight>&nbsp; &nbsp; </device>&nbsp; &nbsp; <device name="24-port switch" quantity="2" serial_number="24PORTSW-004">&nbsp; &nbsp; &nbsp; &nbsp; <weight units="pounds">3.34</weight>&nbsp; &nbsp; </device></device-list>XML;$simpleXml = simplexml_load_string($xml);$weights = array_map(function($elem) {&nbsp; &nbsp; return $elem->__toString();}, $simpleXml->xpath('//weight[@units="pounds"]'));echo "Min: " .min($weights) . "<br/>";echo "Max: " .max($weights);输出:最低:3.00最大值:3.34

慕神8447489

我正在添加这个纯 XPath 1.0 答案,因为在这种情况下,评论中链接的答案是错误的。最大值的一般成语:($node-set[not(. < $node-set)])[1]含义:从节点集中选择第一个(按文档顺序),其数值不小于节点集中的任何其他节点。对于您的输入(现在格式正确):<f:device-list xmlns:f="dummy">&nbsp;&nbsp;&nbsp; <f:device name="Voltage Converter" quantity="2" serial_number="20011">&nbsp;&nbsp; &nbsp; <f:weight units="pounds">3.00</f:weight>&nbsp;&nbsp; </f:device>&nbsp;&nbsp;&nbsp; <f:device name="24-port switch" quantity="2" serial_number="24PORTSW-004">&nbsp;&nbsp; &nbsp; <f:weight units="pounds">3.34</f:weight>&nbsp;&nbsp; </f:device>&nbsp;</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]缩写形式)对位置步轴起作用,这意味着如果集合中的所有节点都是第一个子节点,那么您将需要括号来获得文档顺序中的第一个。
打开App,查看更多内容
随时随地看视频慕课网APP