Moving XML nodes from one document to another


Today’s topic might be of interest for developers that work both in native and managed code, or who are transitioning from one to another.


Moving XML nodes from one document to another is a common operation when you’re merging content, for example, or when a piece of code produces a standalone document that you want to reuse in some other context.


In .NET, XML nodes (attributes, elements, etc.) are always associated with one document. When you want to move the node from one XmlDocument to another, you use the ImportNode method, which creates a copy in the target document, and leaves the source document unchanged. The AppendChild explains how you’ll get an exception if the node was created in the context of another document.


In MSXML, however, you can move the node from one document to another, with the effect that it gets removed from the source document and added to the second document. The following sample code illustrates this.


function createDocumentFromText(xmlText, version) {
  var result = new ActiveXObject(“Msxml2.DOMDocument.” + version);
  result.async = false;
  result.loadXML(xmlText);
  return result;
}

var doc1 = createDocumentFromText(“<book><text>hello</text></book>”, “6.0”);
var doc2 = createDocumentFromText(“<book><text>world</text></book>”, “6.0”);
var book1 = doc1.documentElement;
var text2 = doc2.documentElement.firstChild;
book1.appendChild(text2);

WScript.Echo(doc1.xml);
WScript.Echo(doc2.xml);


This is the result of running the script.


<book><text>hello</text><text>world</text></book>
<book/>


Enjoy!

Comments (0)

Skip to main content