How to change root of a node with DomDocument methods?

后端 未结 5 1123
执念已碎
执念已碎 2021-01-16 10:05

How to only change root\'s tag name of a DOM node?

In the DOM-Document model we can not change the property documentElement of a DOMElement

5条回答
  •  清酒与你
    2021-01-16 10:41

    I hope I am not missing anything but I happened to have the similar problem and was able to solve it by using use DomDocument::replaceChild(...).

       /* @var $doc DOMDocument */
       $doc = DOMImplementation::createDocument(NULL, 'oldRoot');
    
       /* @var $newRoot DomElement */
       $newRoot = $doc->createElement('newRoot');
       /* all the code to create the elements under $newRoot */
    
       $doc->replaceChild($newRoot, $doc->documentElement);
    
       $doc->documentElement->isSameNode($newRoot) === true;
    

    What threw me off initially was that $doc->documentElement was readonly, but the above worked and seems to be much simpler solution IF the $newRoot was created with the same DomDocument, otherwise you'll need do the importNode solution as described above. From your question is appears that $newRoot could be created from the same $doc.

    Let us know if this worked out for you. Cheers.

    EDIT: Noticed in version 20031129 that the DomDocument::$formatOutput, if set, does not format $newRoot output when you finally call $doc->saveXML()

提交回复
热议问题