Adding in new XML root node

左心房为你撑大大i 提交于 2019-12-23 03:15:55

问题


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


来源:https://stackoverflow.com/questions/15284462/adding-in-new-xml-root-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!