如何使用xpath解析此XML以直接获取元素?

时间:2012-10-16 22:37:46

标签: php xpath

  

可能重复:
  Parse XML with Namespace using SimpleXML

我是xpath的新手,无法解析它。它不产生任何输出。

这包含从Google Map API V3返回的XML。我想让它解析并从PostalCode / PostalCodeNumber返回邮政编码。我设置了这个测试,因为我需要能够确保我可以访问PostalCode / PostalCodeNumber,即使Google的API将其他标记放在路上,有时也会这样。因此,让xpath工作非常重要,因为我希望能够直接访问PostalCode / PostalCodeNumber之类的东西,而不依赖于静态树结构路径。请回复,谢谢你的回复!

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<kml xmlns="http://earth.google.com/kml/2.0"><Response>
  <name>40.74445606,-73.97495072</name>
  <Status>
    <code>200</code>
    <request>geocode</request>
  </Status>
  <Placemark id="p1">
    <address>317 E 34th St, New York, NY 10016, USA</address>
    <AddressDetails Accuracy="8" xmlns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"><Country><CountryNameCode>US</CountryNameCode><CountryName>USA</CountryName><AdministrativeArea><AdministrativeAreaName>NY</AdministrativeAreaName><Locality><LocalityName>New York</LocalityName><Thoroughfare><ThoroughfareName>317 E 34th St</ThoroughfareName></Thoroughfare><PostalCode><PostalCodeNumber>10016</PostalCodeNumber></PostalCode></Locality></AdministrativeArea></Country></AddressDetails>
    <ExtendedData>
      <LatLonBox north="40.7458050" south="40.7431070" east="-73.9736017" west="-73.9762997" />
    </ExtendedData>
    <Point><coordinates>-73.9749507,40.7444560,0</coordinates></Point>
  </Placemark>
</Response></kml>
XML;

$xml = new SimpleXMLElement($xml);

$result = $xml->xpath('PostalCode/PostalCodeNumber');

while(list( , $node) = each($result)) {
    echo 'PostalCode/PostalCodeNumber: ',$node,"\n";
}
?>

2 个答案:

答案 0 :(得分:2)

邮政编码位于命名空间中。您必须在XPath表达式中指定名称空间以匹配元素:

$xml = new SimpleXMLElement($xml);
$xml->registerXPathNamespace('urn', 'urn:oasis:names:tc:ciq:xsdschema:xAL:2.0');
$result = $xml->xpath('//urn:PostalCodeNumber');

答案 1 :(得分:0)

使用descendant::PostalCode//PostalCode

请注意,在上面的链接中,我从xml中删除了命名空间定义,以使其工作。 请查看http://www.edankert.com/defaultnamespaces.html#Conclusion以获得明确的解释。

See W3Schools for an easy to understand XPath introduction