Adding in new XML root node

2019-06-08 00:29发布

问题:

I need to add in a new root node to the following XML

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

to become

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

How could I do this? It doesn't seem like SimpleXMLElement has this functionality. I have also looked at this DomNode example http://php.net/manual/en/domnode.insertbefore.php but it doesnt seem to be able to add in a new root node.

回答1:

This seem to work

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

DEMO



回答2:

DOMDocument:

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

Or. if you have your XML as SimpleXMLElement already:

$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);