2012-04-24 89 views
1

具有下一個XML(Idatzi.xml):PHP5和DOM改變XML節點的屬性值

<?xml version='1.0' encoding='ISO-8859-1'?> 
<!DOCTYPE markables SYSTEM "markables.dtd"> 
<markables> 
<markable id="markable_1" atrib="yes" span="word_1..word_4"> </markable> 
<markable id="markable_2" atrib="no" span="word_6..word_7"> </markable> 
<markable id="markable_3" atrib="yes" span="word_10..word_24"> </markable> 
</markables> 

而接下來的PHP代碼:

<?php 

$xmlIdatziDok = new DOMDocument(); 
if($xmlIdatziDok->load("Idatzi.xml") === FALSE){die('Error');} 
$xPath_IdatziDok = new DOMXPath($xmlIdatziDok); 

foreach ($xPath_IdatziDok->query('//markables/markable') AS $Idaztekoa) 
{ 
    $IdaztekoaID = $Idaztekoa->getAttribute('id'); 
    $IdaztekoaAtrib = $Idaztekoa->getAttribute('atrib'); 

    if($IdaztekoaAtrib != "yes") 
    { 
     $Idazteko->Attribute('atrib') = "yes";  
    } 
} 

我想知道如何正確地寫在PHP代碼中的下一行代碼:

$Idazteko->Attribute('atrib') = "yes"; 

這顯然是寫錯了。我想要做的是將markable_2的「否」改爲「是」。任何想法?

回答

4

你可以在documentation找到該信息。

$Idaztekoa->setAttribute('atrib', 'yes'); 
0

使用XPath查詢來直接選擇所有的屬性,你想改變和操縱它們:

foreach($xp->query('/markables/markable/@atrib[. != "yes"]') as $attrib) 
{ 
    $attrib->nodeValue = 'yes'; 
} 

和完成。完整示例:

$xml = <<<XML 
<?xml version='1.0' encoding='ISO-8859-1'?> 
<!DOCTYPE markables SYSTEM "markables.dtd"> 
<markables> 
    <markable id="markable_1" atrib="yes" span="word_1..word_4"> </markable> 
    <markable id="markable_2" atrib="no" span="word_6..word_7"> </markable> 
    <markable id="markable_3" atrib="yes" span="word_10..word_24"> </markable> 
</markables> 
XML; 

$doc = new DOMDocument(); 
$doc->loadXML($xml); 
$xp = new DOMXPath($doc); 

foreach($xp->query('/markables/markable/@atrib[. != "yes"]') as $attrib) 
{ 
    $attrib->nodeValue = 'yes'; 
} 

echo $doc->saveXML();