What is an intuitive way to move an XmlNode from one XmlDocument to another?

I have two XmlDocuments, and I would like to move the XmlNode selected from one of the documents and add it to a specific location in another document.

The naively intuitive approach of simply calling AppendNode (xmlNodeFromDocument1) in the appropriate place in document 2 certainly does not work, because the method does not care about manipulating the ownership of the document.

I finally found the answer literally when I wrote this question, but since it took us so long to find it in the System.Xml classes, I thought I posted it here to help someone else find it.

+3
source share
1 answer

ImportNode , node, . , #.

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);

}
+6

Source: https://habr.com/ru/post/1698051/


All Articles