1

我正在编写一个读取和操作 KML (xml) 文档的脚本。以下是我正在阅读的文档的片段:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated by Feature Manipulation Engine 2009 (Build 5658) -->
<kml xmlns="http://earth.google.com/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
    <Document>
        <name>South Australia</name>
        <visibility>1</visibility>
        <description><![CDATA[Statistical Local Area 2008]]></description>
        <Folder id="kml_ft_SA_SLA08">
            <name>SA_SLA08</name>
            <Placemark id="kml_1">
                <name>Mitcham (C) - West</name>
                <Style>
                    <!-- style info blah blah -->
                </Style>
                <Polygon>
                    <!-- blah blah -->
                </Polygon>
            </Placemark>

            <!-- snip lots more Placemarks -->
        </Folder>
    </Document>
</kml>

我遇到的问题是使用 XPath 从中选择任何内容!

$doc = new DOMDocument();
$doc->load('myfile.xml');    // returns true
$xp = new DOMXPath($doc);

$places = $xp->query("//Placemark");
echo $places->length;         // --> 0 ??!!??
$everything = $xp->query("//*"); // (so I know that the XPath isn't fully borked)
echo $everything->length;    // --> 2085 

这里发生了什么?

4

1 回答 1

5
<?php
$doc = new DOMDocument();
$doc->load('file.xml');    // returns true
$xp = new DOMXPath($doc);
$xp->registerNamespace('ge', 'http://earth.google.com/kml/2.2');

$places = $xp->query("//ge:Placemark");
echo $places->length;         // --> 0 ??!!??
$everything = $xp->query("//*"); // (so I know that the XPath isn't fully borked)

//echo $doc->saveXML();

显然,您必须注册“ge”命名空间并对其进行查询,至少这是我在谷歌搜索几分钟后得出的结论。我想有时我们会忘记我们正在处理命名空间:p

于 2009-09-23T05:34:40.080 回答