views:

297

answers:

1

I have two XmlDocuments and I would like to move an XmlNode selected from one of the documents and append it at a particular location in the other document.

The naively intuitive approach of simply calling AppendNode(xmlNodeFromDocument1) at the appropriate place of document 2, of course doesn't work because the method does not take care of manipulating the owning document.

I finally found the answer literally as I was writing up this question, but since it took so long for us to find it in the System.Xml classes, I figured I'd post it here to assist anyone else stuck searching for it.

+2  A: 

You need to Call ImportNode on the target document to get a node compatible with your target document. The following code illustrates how it is done in C#.

public void CopyExample()
{

   XmlNode nodeFromDifferentDocument = SelectNodeFromSourceDocument();
   XmlDocument targetDocument = InitializeTargetDocument();
   XmlNode targetParentNode = SelectNodesParentWithinTargetDocument(targetDocument);
   bool shouldDodeepCopy = DoIWantADeepCopy();

   XmlNode copyThatBelongsToTargetDocument = 
      targetDocument.ImportNode(nodeFromDifferentDocument, shouldDoDeepCopy);
   targetParentNode.AppendChild(copyThatBelongsToTargetDocument);

}
Michael Lang