2013-03-08 88 views
1

我需要在一個新的根節點添加到下面的XML添加新的XML根節點

<?xml version="1.0"?> 
<unit> 
<source> 
<id>ANCH02</id> 
<uri>http://www.hamiltonisland.biz/tabid/339/Default.aspx</uri> 
</source> 
</unit> 

成爲

<?xml version="1.0"?> 
     <units> 
     <unit> 
     <source> 
     <id>ANCH02</id> 
     <uri>http://www.hamiltonisland.biz/tabid/339/Default.aspx</uri> 
     </source> 
     </unit> 
     </units> 

我怎麼能這樣做?它似乎不像SimpleXMLElement具有此功能。我也看過這個DomNode示例http://php.net/manual/en/domnode.insertbefore.php,但它似乎不能添加到新的根節點中。

+0

示例用'inserBefore':http://codepad.org/vwAP25St – hakre 2013-03-08 04:43:58

回答

4

這似乎工作

$units = $dom->createElement('units'); 
$units->appendChild($dom->documentElement); 
$dom->appendChild($units); 

DEMO

+0

這個偉大的工程- 謝謝! – Franco 2013-03-08 00:46:39

1

DOM文檔:

$yourDOMDOMDocument ... <--- already loaded XML 
$doc = new DOMDocument(); 
$doc->appendChild($doc->createElement('Units')); 
$doc->documentElement->appendChild($doc->importNode($yourDOMDocument->documentElement)); 

或者。如果你有你的XML作爲的SimpleXMLElement已經:

$yourSimpleXML ... <--- already loaded XML 
$doc = new DOMDocument(); 
$doc->appendChild($doc->createElement('Units')); 
$domnode = dom_import_simplexml($yourSimpleXML); 
$doc->documentElement->appendChild($doc->importNode($domnode)); 
//if you want it back as SXE: 
$newSimpleXMLElement = simplexml_import_dom($doc);