开发者

Get root node attributes

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();
$do开发者_开发问答c->load('myfile.xml');
$xpath = new DOMXPath($doc);
$timestamp = $xpath->query("/records@timestamp");

But this gives me an invalid expression error.

What would be the correct PHP/XPath expression syntax to use to obtain the timestamp attribute of the root?


What is your existing PHP code? Are you using DOMDocument? SimpleXML?

The correct Xpath expression is 'string(/records/@timestamp)'

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";
}

?>

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";

?>

EDIT
See edit above. Need to cast to string in the xpath expression

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜