I’m trying to replace a node in one XML document with a node from another XML document. I’m getting the following error:
Insert position node must be a Child of the node to insert under.
This is a simplified version of my XML:
XMLDOC1
<pages>
<page id="1">
<content>First Document</content>
</page>
</pages>
The other XML document is the exact same in structure:
XMLDOC2
<pages>
<page id="1">
<content>Second Document</content>
</page>
</pages>
I need to replace the page node of the first document with the page node of the second document. My attempt looks like this:
firstNode = xmlDoc1.selectSingleNode("//page[@id=1]")
secondNode = xmlDoc2.selectSingleNode("//page[@id=1]")
xmlDoc1.replaceChild(firstNode, oldNode)
Thanks.
Solution
firstNode.parentNode.replaceChild(xmlDoc1.importNode(secondNode, true), firstNode)
The syntax of the
replaceChildis:newChild– An object. The address of the new child that is to replace the old child. If Null, oldChild is removed without a replacement.oldChild– An object. The address of the old child that is to be replaced by the new child.It looks like you have to reverse your arguments. And the node that you run the
replaceChild()on should be the parent of the node you’re replacing. You shouldn’t be running it on thedocument. And finally, since you’re replacing with a node from a different document you should first import it with thexmlDoc1.importNode(secondNode, true). You can also considercloningthe node withcloneNode(deep)before using it in a new context (just so that you had a copy of your own).p.s. shouldn’t it be
secondNodeand not theoldNodein your code snippet?