1

我在 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++;
}
4

1 回答 1

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(),否则调用将仅返回默认命名空间的子级。

于 2013-09-06T15:39:37.827 回答