2 回答

TA貢獻1895條經驗 獲得超7個贊
您可以將所有值映射到一個數組,然后使用max和min函數:
<?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

TA貢獻1780條經驗 獲得超1個贊
我正在添加這個純 XPath 1.0 答案,因為在這種情況下,評論中鏈接的答案是錯誤的。最大值的一般成語:
($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]縮寫形式)對位置步軸起作用,這意味著如果集合中的所有節點都是第一個子節點,那么您將需要括號來獲得文檔順序中的第一個。
- 2 回答
- 0 關注
- 368 瀏覽
添加回答
舉報