使用 SimpleXML 使用命名空间解析 XML

2022-01-14 00:00:00 xml namespaces php simplexml

我有这个作为 xml:

I have this as xml:

<root xmlns:event="http://www.webex.com/schemas/2002/06/service/event">
    <event:event>
        <event:sessionKey></event:sessionKey>
        <event:sessionName>Learn QB in Minutes</event:sessionName>
        <event:sessionType>9</event:sessionType>
        <event:hostWebExID></event:hostWebExID>
        <event:startDate>02/12/2009</event:startDate>
        <event:endDate>02/12/2009</event:endDate>
        <event:timeZoneID>11</event:timeZoneID>
        <event:duration>30</event:duration>
        <event:description></event:description>
        <event:status>NOT_INPROGRESS</event:status>
        <event:panelists></event:panelists>
        <event:listStatus>PUBLIC</event:listStatus>
    </event:event>
    ...
</root>

如何循环遍历所有 event:event 节点并显示,例如,所有 event:SessionKey 的?

How can I loop through all of the event:event nodes and display, for example, all of the event:SessionKey's?

这不起作用:

$xml = new SimpleXMLElement($r);
$xml->registerXPathNamespace('e', 'http://www.webex.com/schemas/2002/06/service/event');

foreach($xml->xpath('//e:event') as $event) {
 var_export($event->xpath('//e:sessionKey'));
}

推荐答案

它确实可以在没有 registerXPathNamespace 和 xpath 查询中的完整命名空间前缀的情况下工作:

it does work without registerXPathNamespace and the full namespace prefix in the xpath queries:

$xml = new SimpleXMLElement($r);

foreach($xml->xpath('//event:event') as $event) {
 var_export($event->xpath('event:sessionKey'));
}

相关文章