获取根节点属性 [英] Get root node attributes
问题描述
我有一个基本结构如下的 XML 文档:
I have an XML document with a basic structure like this:
<?xml version="1.0" encoding="UTF-8" ?>
<records timestamp="1264777862">
<record></record>
<record></record>
<record></record>
<record></record>
</records>
到目前为止,我一直在使用以下内容:
I've been using the following so far:
$doc = new DOMDocument();
$doc->load('myfile.xml');
$xpath = new DOMXPath($doc);
$timestamp = $xpath->query("/records@timestamp");
但这给了我一个无效的表达式错误.
But this gives me an invalid expression error.
用于获取根的时间戳属性的正确 PHP/XPath 表达式语法是什么?
What would be the correct PHP/XPath expression syntax to use to obtain the timestamp attribute of the root?
推荐答案
您现有的 PHP 代码是什么?你在使用 DOMDocument 吗?简单 XML?
What is your existing PHP code? Are you using DOMDocument? SimpleXML?
正确的 Xpath 表达式是 'string(/records/@timestamp)'
The correct Xpath expression is 'string(/records/@timestamp)'
对于 SimpleXML,请参见 http://php.net/manual/en/simplexmlelement.xpath.php例如
For SimpleXML see http://php.net/manual/en/simplexmlelement.xpath.php e.g.
<?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
And for DOMXPath see 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 表达式中强制转换为字符串
EDIT
See edit above. Need to cast to string in the xpath expression
这篇关于获取根节点属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!