考虑以下XML:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<myResponse xmlns="https://example.com/foo">
<myResult xmlns:a="https://example.com/bar" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:accountNumber>AAA</a:accountNumber>
<a:accountName>BBB</a:accountName>
<a:accountType>CCC</a:accountType>
</myResult>
</myResponse>
</s:Body>
</s:Envelope>
我正在尝试选择myResult和它下面的所有元素。
我得到的最接近的是:
//*[local-name()='myResult']//a:*
这让我得到了元素的值,但我不知道哪个值属于哪个元素。
我是用PHP做这件事的,下面是(大致)我正在使用的代码:
<?php
$xmlObject = new SimpleXMLElement($result);
$namespaces = $xmlObject->getNamespaces(true);
foreach($namespaces as $key => $value) {
if($key == '') {
$key = 'ns';
}
$xmlObject->registerXPathNamespace($key, $value);
}
$element = $xmlObject->xpath("//myResult");
?>
我知道有很多关于XPath和XML名称空间的问题(哦,我是如何搜索的),但我还没有找到一个与我的特定情况相匹配的问题。我想做的事情有可能吗?
您的//*[local-name()='myResult']//a:*
运行良好。您只需要循环并使用getName
来获取标记的名称。
$element = $xmlObject->xpath("//*[local-name()='myResult']//a:*");
foreach($element as $e){
echo $e->getName() . ': '. (string)$e;
}
演示:http://codepad.org/BAefIKZ4
EDIT:既然您正在注册名称空间,为什么不使用它们呢?
$element = $xmlObject->xpath("//ns:myResult//a:*");
演示:http://codepad.org/9MKq5oDt
当您将默认命名空间定义为"ns"时,请使用:
$element = $xmlObject->xpath("//ns:myResult");