我有一个具有以下基本结构的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");
但这给了我一个无效的表达错误。
用于获取根的timestamp属性的正确PHP / XPath表达式语法是什么?
最佳答案
您现有的PHP代码是什么?您正在使用DOMDocument吗? SimpleXML?
正确的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表达式中强制转换为字符串
关于xml - 获取根节点属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2162986/