2011-11-09 127 views
1

如何通過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: 
+0

你的XML對'records',一個在'record'的屬性。你想和誰一起工作? –

+0

對不起,我的錯誤。請參閱我上面的編輯。謝謝。 – laukok

回答

4

一種方法:

$nodes = $xpath->query('//records[@timestamp]'); 
foreach($nodes as $node) { 
    $timestamp = $node->getAttribute('timestamp'); 
} 

雖然,您在示例中混合了recordrecords,所以我不確定您在實際中使用了哪個。


更新:此代碼的工作對我來說:

<?php 

$xml = <<<EOL 
<?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> 
EOL; 

$x = new DOMDocument(); 
$x->loadXML($xml); 

$xp = new DOMXpath($x); 

$nodes = $xp->query('//records/record'); 
foreach($nodes as $node) { 
    echo $node->nodeValue, ': ', $node->getAttribute('timestamp'), "\n"; 
} 

和輸出

A: 1264777862 
B: 
C: 1264777000 
D: 
+0

對不起,我的錯誤。請參閱我上面的編輯。我用'getAttrribute'得到一個錯誤信息,謝謝。 – laukok

+0

woops。錯字。應該是getAttribute(一個r)。 –

+0

對不起,我剛剛意識到另一個問題,因爲我需要結果中的更多信息。我不能在你的答案中使用查詢。你能看到我上面的修改嗎?謝謝。 – laukok

相關問題