使用冒号 - 嵌套结构(php和simpleXML)解析xml

时间:2013-09-06 15:10:46

标签: php simplexml xml-namespaces

我在PHP中使用simpleXML解析xml存在严重问题,因为根元素和子元素的名称都有冒号。我已经搜索了许多解决方案并找到了一个有效的解决方案。但是,我的问题更具体,因为这些冒号元素是嵌套的。

如您所见,根元素的子元素可以在1到N之间变化(原始xml的片段):

     <bpmndi:BPMNEdge bpmnElement="sid-96E075E5-D515-46E7-BED2-9A284F1F5153" id="sid-96E075E5-D515-46E7-BED2-9A284F1F5153_gui">
        <omgdi:waypoint x="985.0" y="220.0"/>
        <omgdi:waypoint x="1055.5" y="220.0"/>
        <omgdi:waypoint x="1055.5" y="160.0"/>
     </bpmndi:BPMNEdge>
     <bpmndi:BPMNEdge bpmnElement="sid-F36DC404-7095-4653-8176-FB99ADAB8DEC" id="sid-F36DC404-7095-4653-8176-FB99ADAB8DEC_gui">
        <omgdi:waypoint x="927.0" y="580.0"/>
        <omgdi:waypoint x="1005.0" y="580.0"/>
     </bpmndi:BPMNEdge>

我目前所做的事情(并且有效,问题出在代码的评论部分)

$xml->registerXPathNamespace('bpmndi', 'specific-url');
$xml->registerXPathNamespace('omgdi', 'specific-url');
$edges = $xml->xpath('//bpmndi:BPMNEdge');
$point = $xml->xpath('//omgdi:waypont');

$i = 0;
foreach ($edges as $edge) {

echo (string) $edge[0]['bpmnElement'];  
//how to get the children of this element? E.g. 1 or N waypoints and their x and y?
$i++;
}

1 个答案:

答案 0 :(得分:2)

您可以轻松迭代元素的children()(请参阅http://php.net/simplexmlelement.children):

foreach($edge->children('omgdi', true) as $child) {
    echo sprintf("waypoint %s / %s\n", $child->attributes()->x, $child->attributes()->y);
}

调用children()时必须提供命名空间,否则调用只返回默认命名空间的子节点。