What is the easiest way to merge XML from two distinct DOM Documents? Is there a way other than using the Canonical DataReader approach and then messing with the outputted DOM. What I basically want is to AppendChild to XmlElements without getting: The node to be inserted is from a different document context. Here is C# code that I want to work, that obviously won’t (what I am doing is merging two documents which have bunch of nodes that I am interested in parts of):
XmlDocument doc1 = new XmlDocument(); doc1.LoadXml('<a><items><item1/><item2/><item3/></items></a>'); XmlDocument doc2 = new XmlDocument(); doc2.LoadXml('<b><items><item4/><item5/><item6/></items></b>'); XmlNode doc2Node = doc2.SelectSingleNode('/b/items'); XmlNodeList doc1Nodes = doc1.SelectNodes('/a/items/*'); foreach (XmlNode doc1Node in doc1Nodes) { doc2Node.AppendChild(doc1Node); }
You can use the XmlDocument.ImportNode method to copy a node from a XmlDocument to another.