获取多个名称空间xml中的元素

时间:2014-12-02 11:37:09

标签: php xml xpath xml-parsing xml-namespaces

我试图在名称空间`// ns1:Location // ns1:District中获取元素DistrictName但是没有返回任何内容。这是我到目前为止所做的。

foreach($xml1->xpath('//ns1:Venue') as $header){
    $result = ($header->xpath('//ns1:Venue//ns1:Location//ns1:District//ns1:DistrictName')); // Should output 'something'.
    echo "Local2: " . (string) $result[0]. "</br>";
}

soap_response_xml:

...
<ns1:Venue>
  <ns1:Name>Rock</ns1:Name>
  <ns1:Contact>
    <ns1:Name>Rock</ns1:Name>
  </ns1:Contact>
  <ns1:Location>
    <ns1:District>
      <ns2:DistrictId>11</ns2:DistrictId>
      <ns2:DistrictName>XXXXXXX</ns2:DistrictName>
    </ns1:District>
    <ns1:Municipaly>
      <ns2:MunicipalityId>1111</ns2:MunicipalityId>
      <ns2:MunicipalityName>XXXXXXXXX</ns2:MunicipalityName>
    </ns1:Municipaly>
  </ns1:Location>
</ns1:Venue>

我做错了什么?

1 个答案:

答案 0 :(得分:1)

如果您的XML是字符串,最简单的可能是删除名称空间:

$string = str_replace(array('ns1:', 'ns2:'), array('', ''), $string);
$xml = new SimpleXMLElement($string);
foreach($xml->xpath('//Venue') as $header){
    $result = ($header->xpath('Location/District/DistrictName')); // Should output 'something'.
    echo "Local2: " . (string) $result[0]. "</br>";
}

另外:如果没有必要,请不要使用////表示“后代”。路径分隔符为/