DOM XPath Query Help
so this xpath query is driving me crazy. What I'm trying to do is search an xml file (in this case a kml file for use with the google maps api) of golf courses for a specific course type and grab each matching <Placemark>
element so that i can create a new xml object with the results so that I can further filter with a new query. Problem is I can't seem to figure out how to get each matching <Placemark>
element
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
<Placemark id="placemark3">
<name>Test Country Club</name>
<description>
<![CDATA[
<div class="contact">Post Office Box 329 <a href="#" target="_blank">website</a></div>
]]>
</description>
<alpha>a</alpha>
<position>2</position>
<t开发者_Python百科ype>Public/Daily Fee</type>
<styleUrl>#nineholeStyle</styleUrl>
<Point>
<coordinates>-79.285576,37.111809</coordinates>
</Point>
</Placemark>
</Document>
</kml>';
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
//trying to get any Placemark element where type child matches a specific query
//in this case we want to search for Public/Daily Fee and return the placemark and everything inside it.
$query = $xpath->query("//Placemark[type='Public/Daily Fee']/ancestor::Placemark");;
foreach ($query as $result) {
//eventually want to merge each result into new xml object to be further filtered
}
Any help would be greatly appreciated. Thanks
You did not register the XML namespace before the query.
// register it
$xpath->registerNamespace('kml', "http://earth.google.com/kml/2.1");
// and use it, too !
$query = $xpath->query("//kml:Placemark[kml:type='Public/Daily Fee']");
(the ancestor::kml:Placemark
in your expression made no sense, I left it out.)
The namespace prefix in the XPath query must be used even if the namespace in question is the default namespace of the XML document (like in your case).
The element <kml xmlns="http://earth.google.com/kml/2.1">
is equivalent to <kml:kml xmlns:kml="http://earth.google.com/kml/2.1"
>.
However, an XPath query of /kml
is not equivalent to /kml:kml
. The latter would match both elements (when the kml
namespace is registered beforehand), the former would match none of them, no matter what you do.
Also note that you do not need to use the same namespace prefix that is used in the XML document.
Assume the XML document is this:
<kml:kml xmlns:kml="http://earth.google.com/kml/2.1">
<kml:Document />
</kml:kml>
Then you could still do this:
$xpath->registerNamespace('foo', "http://earth.google.com/kml/2.1");
$query = $xpath->query("/foo:kml/foo:Document");
and get back a correct result. Namespace prefixes are just a shorthand.
精彩评论