【问题标题】:Get root node attributes获取根节点属性
【发布时间】:2010-01-29 15:37:42
【问题描述】:

我有一个基本结构如下的 XML 文档:

<?xml version="1.0" encoding="UTF-8" ?>
<records timestamp="1264777862">
<record></record>
<record></record>
<record></record>
<record></record>
</records>

到目前为止,我一直在使用以下内容:

$doc = new DOMDocument();
$doc->load('myfile.xml');
$xpath = new DOMXPath($doc);
$timestamp = $xpath->query("/records@timestamp");

但这给了我一个无效的表达式错误。

获取根的时间戳属性的正确 PHP/XPath 表达式语法是什么?

【问题讨论】:

  • 见下面我的表达。你需要 / 在 /records/@timestamp

标签: xml xpath


【解决方案1】:

您现有的 PHP 代码是什么?你在使用 DOMDocument 吗?简单XML?

正确的 Xpath 表达式是 'string(/records/@timestamp)'

对于 SimpleXML,请参阅 http://php.net/manual/en/simplexmlelement.xpath.php 例如

<?php
$string = <<<XML
<records timestamp="1264777862">
<record></record>
<record></record>
<record></record>
<record></record>
</records>

XML;

$xml = new SimpleXMLElement($string);

$result = $xml->xpath('string(/records/@timestamp)');

while(list( , $node) = each($result)) {
    echo $node,"\n";
}

?>

对于 DOMXPath,请参阅 http://www.php.net/manual/en/domxpath.evaluate.php

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// our query is relative to the records node
$query = 'string(/records/@timestamp)';

$timestamp = $xpath->evaluate($query);
echo $timestamp ."\n";

?>

编辑
请参阅上面的编辑。需要在 xpath 表达式中强制转换为字符串

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多