duanheye7423 2009-09-23 05:22
浏览 16
已采纳

Simplexml XPath奇怪

I'm writing a script which reads and manipulates a KML (xml) document. Below is a snippet of the document I'm reading:

<?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>

The problem I'm having is with using XPath to select anything from it!

$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 

What's going on here?

  • 写回答

1条回答 默认 最新

  • duanchifo2866 2009-09-23 05:34
    关注
    <?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();
    

    Apparently you have to register the 'ge' namespace and query it as such, at least this is what I came up with after a few minutes googling. I guess sometimes we forget we're dealing with namespaces :p

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度