在PHP中重命名XML DOM节点

时间:2011-09-03 17:57:55

标签: php xml dom

如何在DOMDocument中重命名XML节点?我想在编写新节点之前备份XML文件中的节点。我有这个代码,我想将URLS节点重命名为URLS_BACKUP。

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>

感谢。

3 个答案:

答案 0 :(得分: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 :(得分:2)

无法重命名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();

答案 2 :(得分:0)

知道这是不可能的,这是一个更简单的功能,用于在保存文件后重命名标记:

/**
 * renames a word in a file
 *
 * @param string $xml_path
 * @param string $orig word to rename
 * @param string $new new word
 * @return void
 */
public function renameNode($xml_path,$orig,$new)
{
    $str=file_get_contents($xml_path);
    $str=str_replace($orig, $new ,$str);
    file_put_contents($xml_path, $str);
}
相关问题