When working with different XML documents one may require transferring nodes from one document to another. To do this, find a node in the first document and add it to the second one using the appendChild method of the IXmlDomNode interface. If it is required to replace the existing node, use the replaceChild method. In this case the node used for replacement should also be added to the target document using the appendChild method.
Sub TestReplace;
Var
doc1, doc2: IXMLDOMDocument2;
node1, node2: IXmlDomNode;
root1, root2: IXMLDOMElement;
Begin
// First document
doc1 := New DOMDocument.Create;
doc1.loadXML("<doc><node1/></doc>");
root1 := doc1.documentElement;
node1 := root1.selectSingleNode("node1");
Debug.WriteLine("Doc1 before: " + doc1.xml);
// Second document
doc2 := New DOMDocument.Create;
doc2.loadXML("<doc><node2/></doc>");
root2 := doc2.documentElement;
node2 := root2.selectSingleNode("node2");
// Replace node in the first document with node from the second document
root1.appendChild(node2);
root1.replaceChild(node2, node1);
Debug.WriteLine("Doc1 after: " + doc1.xml);
// Free variables
Dispose doc1;
Dispose doc2;
End Sub TestReplace;
The specified example displays creating of two new XML documents from the character string. To replace the node in the first document, the node from the second document is added to the first document. After this the first node is replaced with the second one. XML views of the first document before and after replacement are displayed in the development environment console.
See also: