【问题标题】:Using xPath for sitemap.xml对 sitemap.xml 使用 xPath
【发布时间】:2014-05-21 12:38:57
【问题描述】:

这里是 XML 文件内容:

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url id="first_url">
<loc>http://example.com</loc>
<lastmod>2014-05-21</lastmod>
</url>
</urlset>

这里是 PHP 代码:

<?php
$dom = new DOMDocument('1.0', 'utf-8');
$dom->Load('sitemap.xml');
$xpath = new DOMXPath($dom);        
$tags = $xpath->query('//url[@id="first_url"]');
foreach($tags as $tag)
    print $tag->getAttribute("id")."<br/>";
?>

此代码不起作用。但是如果我从文件中删除xmlns="http://www.sitemaps.org/schemas/sitemap/0.9",它就可以工作。为什么会这样?谢谢!

【问题讨论】:

    标签: php xml xpath sitemap


    【解决方案1】:

    这是因为命名空间。这是忽略名称空间的方法:

    Xpath 1.0:

    //*[local-name()="url"][@id="first_url"]
    

    Xpath 2.0:

    //*:url[@id="first_url"]
    

    【讨论】:

      【解决方案2】:

      使用DOMXPath::registerNamespace注册命名空间

      $xpath->registerNamespace("s",
              "http://www.sitemaps.org/schemas/sitemap/0.9");
      

      然后在你的 XPath 中使用它:

      $tags = $xpath->query('//s:url[@id="first_url"]');
      

      【讨论】:

        猜你喜欢
        • 2016-07-19
        • 1970-01-01
        • 2014-07-14
        • 1970-01-01
        • 2011-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-04
        相关资源
        最近更新 更多