我有一个像这样的XML文件:
<devices>
<device name="Cabina" altid="e2" id="42" category="3"
subcategory="0" room="3" parent="40" status="1" state="-1" comment=""/>
<device name="contatto finestra cucina" altid="12" id="28" category="4"
subcategory="3" room="1" parent="1" armed="0" tripped="1"
lasttrip="1398337234" batterylevel="1" heatsp="19" status="1"/>
<device name="Ingresso" altid="e1" id="15" category="3"
subcategory="0" room="1" parent="14" status="0" state="-1" comment=""/>
</devices>
我想总结属于类别3的设备的状态。
在这种情况下,sum = 1。
由于
答案 0 :(得分:3)
使用XPath表达式:
选择设备节点:/devices/device
如果category属性为3:/devices/device[@category = 3]
获取状态属性:/devices/device[@category = 3]/@status
总结一下:sum(/devices/device[@category = 3]/@status)
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
var_dump($xpath->evaluate('sum(/devices/device[@category = 3]/@status)'));
float(1)
答案 1 :(得分:1)
$xml = simplexml_load_file('example.xml');
$sum=0;
foreach($xml as $device)
{
if($device->category==3)
{
$sum+=$device->status;
}
}
echo $sum;