【问题标题】:Getting attribute value from DOMXPath query result? [duplicate]从 DOMXPath 查询结果中获取属性值? [复制]
【发布时间】:2013-04-06 10:53:24
【问题描述】:

我正在尝试搜索 XML 文件并返回与给定条件匹配的记录的所有数据。这是我现在拥有的东西,它搜索得很好,但我似乎无法弄清楚如何在同一条记录中获取其他属性的值。

下面是一个使用的 XML 文件示例:

<routing>
    <route>
        <url>/homepage</url>
        <file>/pages/home.php</file>
    </route>
</routing>

以下是我在文档中查找特定记录的方法。它完美地找到了它们,但是如何从匹配的记录中获取数据?

    $qExp = '//route[url="/homepage"]';
    foreach($inst->query($qExp) as $key=>$node) {
        print_r($node);
        // echo $node->file->nodeValue;
        // how would I do this? I can't seem to
        // access specific attributes at all
        // inside of the DOMXPath class
    }

一个 DOMXPath 对象将存储在$node 中,但是如何使用DOMXPath 对象来获取其他属性值?例如,此查询将返回第一条 XML 记录,但我如何具体获取 file 属性的值?我知道有一个可用的nodeValue 函数,但它会将所有字段的值一起返回,我无法对哪些部分属于哪些字段进行排序。

提前感谢您的帮助,这真的让我很烦恼。

【问题讨论】:

  • 您可能会因为混淆了这些术语而感到困惑? file 不是一个属性而是一个元素。您可以按照Get a specific child tag from a DOMElement in PHP 中的说明正常访问它。此外,猜测的$node-&gt;file-&gt;nodeValue 是两种不同遍历的混合体:首先是 SimpleXML,然后是 DOM。
  • 另一个小错误是你说$nodeDOMXPath,但它是DOMNode

标签: php xml dom domdocument domxpath


【解决方案1】:

对于一个简单的解决方案,请使用simplexml

$xml = simplexml_load_string($x); // assuming XML in $x
$result = $xml->xpath("//route[url='/homepage']");

// loop
foreach ($result as $r) echo $r->file,"<br />";

// direct access
echo $result[0]->file,"<br />";

观看现场演示@http://codepad.viper-7.com/ZRrUPl

【讨论】:

  • 你好??为什么投反对票??请解释!
猜你喜欢
  • 2014-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多