DomXml fetch root element

liunx

Guest
Hello,

my problem is quite simple. The goal is to insert the content of two DOMDocuments into one. I tried the following:

$oOldRootElem1 = $oExistingDOM1->documentElement;
$oOldRootElem2 = $oExistingDOM2->documentElement;

// now we create the new DOM
$oDoc = new DOMDocument('1.0');
$oRoot = $oDoc->createElement('newroot');
$oRoot = $oDoc->appendChild($oRoot);
$oOldRootElem1= $oRoot->appendChild($oOldRootElem1);
$oOldRootElem2= $oRoot->appendChild($oOldRootElem2);


when running this code I get the error 'Wrong Document Error'.
Can anybody help?

thx
SebastianI'm guessing that it would be because the $oOldRootElems are belong to the existing DOMDocuments, and not the new one (nodes remember which document they belong to, otherwise things like "insertAfter" wouldn't make sense). In that case, you'll be wanting to use importNode to get the "old roots" into the document, and then append the imported nodes.

$dExistingDOM1 = DOMDocument::loadXML('<root><node/></root>');
$dExistingDOM2 = DOMDocument::loadXML('<foo><bar/></foo>');

$nOldRoot1 = $dExistingDOM1->documentElement;
$nOldRoot2 = $dExistingDOM2->documentElement;

// now we create the new DOM
$dDoc = new DOMDocument('1.0');
$nRoot = $dDoc->createElement('newroot');
$nRoot = $dDoc->appendChild($nRoot);
$nNewRoot1 = $dDoc->importNode($nOldRoot1,true); // here we import; use "true" so that
$nNewRoot2 = $dDoc->importNode($nOldRoot2,true); // descendent nodes are imported also
$nNewRoot1= $nRoot->appendChild($nNewRoot1);
$nNewRoot2= $nRoot->appendChild($nNewRoot2);this was exactly the problem. Thank you! My personal object orientated approach to DOMXML would be that elements are objects and can be moved from one DOM to the other but aparently the guys who programmed this, did not have the same opinion ;)Well, like I noted, one of the properties of a DOM node is its owner document; so that if you have a node you can determine things like its parent node and containing document - otherwise traversal would be a nightmare.
 
Back
Top