如何通过xpath获取每个节点的属性?如何通过xpath获取每个节点的属性
例如,
是book.xml,
PHP,
<?php
$doc = new DOMDocument;
$doc->load('book.xml');
$xpath = new DOMXPath($doc);
# get and output "<entry>" elements
$x = $doc -> getElementsByTagName('record');
# Count the total feed with xpath.
$total = $x->length;
# the query is relative to the records node
$query = 'string(/records/@timestamp)';
for ($i=0; $i<$total; $i++)
{
$timestamp = $xpath->evaluate($query,$x->item($i));
echo $timestamp ."<br/>";
}
?>
结果(它仅循环的第一个节点),
1264777862
1264777862
1264777862
1264777862
但我想得到,
1264777862
1264777000
我已按照here的问题和答案进行了修改。
或者也许有更好的方法?
编辑:
XML,
<?xml version="1.0" encoding="UTF-8" ?>
<records>
<record timestamp="1264777862">A</record>
<record>B</record>
<record timestamp="1264777000">C</record>
<record>D</record>
</records>
与此,
for ($i=0; $i<$total; $i++)
{
$value = $x->item($i)->childNodes->item(0)->nodeValue;
$timestamp = $xpath->evaluate($query,$x->item($i));
echo $value.': '.$timestamp ."<br/>";
}
我得到这样的结果,
A: 1264777862
B: 1264777862
C: 1264777862
D: 1264777862
但这是结果我之后,
A: 1264777862
B:
C: 1264777862
D:
编辑:
测试,
$nodes = $xpath->query('//records/record');
foreach($nodes as $node) {
$value = $node->nodeValue;
$timestamp = $node->getAttribute('timestamp');
echo $value .': '."<br/>";
}
结果,
A:
B:
C:
D:
你的XML对'records',一个在'record'的属性。你想和谁一起工作? –
对不起,我的错误。请参阅我上面的编辑。谢谢。 – laukok