tags:

views:

1365

answers:

2

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);
    }
+4  A: 

You can use the XmlDocument.ImportNode method to copy a node from a XmlDocument to another.

ckarras
Just what I was looking for...
Kris Erickson
http://php.net/domdocument.importnode
sirlancelot
+1  A: 

You might be interested in http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.importnode.aspx. But take a close look at the "The following table describes the specific behavior for each XmlNodeType."-part of that document.

VolkerK