用多个命名空间解析XML [英] Parsing XML with multiple namespaces
问题描述
所以我想解析这个XML:
So I wanted to parse this XML:
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<requestContactResponse xmlns="http://webservice.foo.com">
<requestContactReturn>
<errorCode xsi:nil="true"/>
<errorDesc xsi:nil="true"/>
<id>744</id>
</requestContactReturn>
</requestContactResponse>
</soapenv:Body>
</soapenv:Envelope>
具体来说,我想获取标签的价值< id>
Specifically I want to get the value of the tag <id>
这是我试过的:
$dom = new DOMDocument;
$dom->loadXML($xml);
$dom->children('soapenv', true)->Envelope->children('soapenv', true)->Body->children()->requestContactResponse->requestContactReturn->id;
但是我收到此错误消息:
But I get this error message:
PHP致命错误:调用未定义的方法DOMDocument :: children()
PHP Fatal error: Call to undefined method DOMDocument::children()
我也试过使用simpleXML:
I've also tried to use simpleXML:
$sxe = new SimpleXMLElement($xml);
$sxe->children('soapenv', true)->Envelope->children('soapenv', true)->Body->children()->requestContactResponse->requestContactReturn->id;
但是我收到这个其他错误信息:
But I get this other error message:
PHP致命错误:调用非对象的成员函数children()
PHP Fatal error: Call to a member function children() on a non-object
最后解决方案我试过:
$sxe = new SimpleXMLElement($xml);
$elements = $sxe->children("soapenv", true)->Body->requestContactResponse->requestContactReturn;
foreach($elements as $element) {
echo "|-$element->id-|";
}
这次错误消息是:
Invalid argument supplied for foreach()
任何建议?
推荐答案
在这里播放的文件不足之处在于,当您使用 - > children
,它对于后代节点仍然有效。
The poorly documented fact in play here is that when you select a namespace with ->children
, it remains in effect for descendent nodes.
所以当你要求 $ sxe-> children(soapenv,true) - > Body-> requestContactResponse
,SimpleXML假定您仍在谈论soapenv / code>命名空间,所以寻找元素
< soapenv:requestContactResponse>
,不存在。
So when you ask for $sxe->children("soapenv", true)->Body->requestContactResponse
, SimpleXML assumes you are still talking about the "soapenv"
namespace, so is looking for the element <soapenv:requestContactResponse>
, which doesn't exist.
要切换回默认命名空间,您需要再次调用 - > children
, NULL
namespace:
To switch back to the default namespace, you need to call ->children
again, with a NULL
namespace:
$sx->children("soapenv", true)->Body->children(NULL)->requestContactResponse->requestContactReturn->id
这篇关于用多个命名空间解析XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!