php - 简单的 xpath 查询但没有结果

标签 php xpath

尝试从 xml 获取所有 URL 值。

我有数百个条目,其形式完全相同,例如此条目16:

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <entries>
   <entry id="16">
      <revision number="1" status="accepted" wordclass="v" nounclasses="" unverified="false"></revision>
      <media type="audio" url="http://website.com/file/65.mp3" />
      </entry>
   <entry id="17">
      ....
   </entry>
</entries>
</root>

我正在使用此代码,但无法使其工作。为什么?

$doc = new DOMDocument;

$doc->Load('data.xml');

$xpath = new DOMXPath($doc);

$query = '//root/entries/entry/media';

$entries = $xpath->query($query);

正确的查询是什么?最好是只获取 url 值。

最佳答案

您的查询可能会返回正确的元素,但默认情况下会为您提供媒体标记的内容(在您的情况下,该内容为空,因为该标记是自闭合的)。

要获取标签的 url 属性,您应该使用 getAttribute(),例如:

$entries = $xpath->query('//root/entries/entry/media');
foreach($entries as $entry) { 
  print $entry->getAttribute("url")."<br/>";
}

或者您应该只通过 xpath 查询该属性并读出它的值:

$urlAttributes = $xpath->query('//root/entries/entry/media/@url');
                                                          #####
foreach ($urlAttributes as $urlAttribute)
{ 
    echo $urlAttribute->value, "<br/>\n";
                        #####
}

参见DOMAttr::$valueDocs :

value


The value of the attribute

关于php - 简单的 xpath 查询但没有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15483285/

相关文章:

php - 在 PHP 中检索当前函数的名称

php - Products 和 Product 命名空间破坏了我的 xpath

php - 使用 XMLReader、DOM、Xpath 获取给定节点的标签名称和值

php - 如何从codeigniter项目中的url中删除index.php

php - 图返回错误 : Can't Load URL: The domain of this URL isn't included in the app's domains

php - 找不到 Symfony 3 方法 'guessExtension()' 和 'move()'

php - 使用 AWS 进行 SQL 和 REST 前端

java - 无法使用 XPath 获取 XML 的节点值

selenium - 多个值的 xpath OR 运算符

Python ElementTree - 按顺序遍历子节点和文本