2011-09-03 131 views
0

如何重命名DOMDocument中的XML節點?在編寫新節點之前,我想在XML文件中對節點進行備份。我有這個代碼,我想將URLS節點重命名爲URLS_BACKUP。在PHP中重命名XML DOM節點

function backup_urls($nodeid) { 

$dom = new DOMDocument(); 
$dom->load('communities.xml'); 

$dom->formatOutput = true; 
$dom->preserveWhiteSpace = true; 

// get document element 

$xpath = new DOMXPath($dom); 
$nodes = $xpath->query("//COMMUNITY[@ID='$nodeid']"); 

if ($nodes->length) { 

    $node = $nodes->item(0); 

    $xurls = $xpath->query("//COMMUNITY[@ID='$nodeid']/URLS"); 

    if ($xurls->length) { 
    /* rename URLS to URLS_BACKUP */ 

    } 

} 

$dom->save('communities.xml'); 
} 

XML文件具有這種結構。

<?xml version="1.0" encoding="ISO-8859-1"?> 
<COMMUNITIES> 
<COMMUNITY ID="c000002"> 
    <NAME>ID000002</NAME> 
    <TOP>192</TOP> 
    <LEFT>297</LEFT> 
    <WIDTH>150</WIDTH> 
    <HEIGHT>150</HEIGHT> 
    <URLS> 
    <URL ID="u000002"> 
     <NAME>Facebook.com</NAME> 
     <URLC>http://www.facebook.com</URLC> 
    </URL> 
    </URLS> 
</COMMUNITY> 
</COMMUNITIES> 

謝謝。

+0

必須使用replaceNode但你必須創建新的節點URL_BACKUP和克隆礦石副本的所有兒童在此節點表格前URLC – ZigZag

+0

@ user900898所以唯一的辦法就是使節點的新副本,所有這一切嵌套在它。沒有重命名。我必須複製然後刪除,如果我想刪除舊的節點。謝謝。 – user823527

回答

6

你閱讀的fopen xml文件的整個列表,你所用的方法str_replace()函數

$ handle = fopen ('communities.xml', 'r'); 
while (! feof ($ handle)) 
{ 
     $ buffer = fgets ($ handle, 4012); 
     $ buffer = str_replace ("URLS", "URLS_BACKUP", $ buffer); 
} 
fclose ($ handle); 
$ dom-> save ('communities.xml'); 
1

這是不可能的DOM重命名節點。字符串函數可能工作,但最好的解決方案是創建一個新節點並替換舊節點。

$dom = new DOMDocument(); 
$dom->loadXml($xml); 
$xpath = new DOMXPath($dom); 

$nodeId = 'c000002'; 
$nodes = $xpath->evaluate("//COMMUNITY[@ID='$nodeid']/URLS"); 

// we change the document, iterate the nodes backwards 
for ($i = $nodes->length - 1; $i >= 0; $i--) { 
    $node = $nodes->item($i); 
    // create the new node 
    $newNode = $dom->createElement('URL_BACKUP'); 
    // copy all children to the new node 
    foreach ($node->childNodes as $childNode) { 
    $newNode->appendChild($childNode->cloneNode(TRUE)); 
    } 
    // replace the node 
    $node->parentNode->replaceChild($newNode, $node); 
} 

echo $dom->saveXml();