通过XPath从子级和父级提取属性值

时间:2018-11-01 19:03:17

标签: php xml xpath

如何通过XPath提取父级和子级属性的值?

示例XML文件为:

<?xml version="1.0" encoding="UTF-8"?>
<detail month="9" year="2018">
    <subService desc="Voice" parent="1" service="V">
        <item qnt="67" period="02" time="18:51" date="2018-09-04"></item>
        <item qnt="93" period="02" time="13:02" date="2018-09-07"></item>
    </subService>
    <subService desc="Voice" parent="11" service="V">
        <item qnt="60" period="02" time="11:09" date="2018-09-19"></item>
        <item qnt="60" period="02" time="10:19" date="2018-09-04"></item>
    </subService>
    <subService desc="Data" parent="55" service="D">
        <item qnt="7200" period="01" time="00:00" date="2018-09-14"></item>
        <item qnt="21600" period="01" time="00:00" date="2018-09-14"></item>
    </subService>
</detail>

这是我用来从孩子那里收集数据的代码,但我也需要从父母那里收集数据。

<?php
$id=1; 
$xml=simplexml_load_file("./data/test3.xml") or die("Error: Cannot create object");
$result = $xml->xpath("//subService/item");    
foreach($result as $key => $value)  {
    $quantity=$value['qnt'];
    $period=$value['period'];
    $date=$value['time'];
    $time=$value['date'];
    echo "$id,$parent,$service,$quantity,$period,$date,$time <br>";
    $id=($id+1);
}
?> 

这就是我想要的输出:

1,1,V,67,02,18:51,2018-09-04
2,1,V,93,02,13:02,2018-09-07 
3,11,V,60,02,11:09,2018-09-19
4,11,V,60,02,10:19,2018-09-04 
5,55,D,7200,01,00:00,2018-09-14 
6,55,D,21600,01,00:00,2018-09-14

非常感谢您

1 个答案:

答案 0 :(得分:0)

我发现使用SimpleXML时更容易从顶层开始获取XML。这涉及一个额外的循环-从<subService>元素开始,每个<item>的内部循环。这使得对各种元素的访问尽可能简单(对于以后的编码人员来说是显而易见的)...

$result = $xml->xpath("//subService");
foreach($result as $value)  {
    $parent = $value['parent'];
    $service = $value['service'];
    foreach ( $value->item as $item )   {
        $quantity=$item['qnt'];
        $period=$item['period'];
        $date=$item['time'];
        $time=$item['date'];
        echo "$id,$parent,$service,$quantity,$period,$date,$time <br>";
        $id++;
    }
}

如果这是您的实际XML格式,我很想完全删除XPath并继续...

//$result = $xml->xpath("//subService");
foreach($xml->subService as $value)  {