insert XmlDocument into a XmlDocument node

Rodniko picture Rodniko · Oct 6, 2010 · Viewed 8.2k times · Source

I created a basic XmlDocument with one node:

XmlDocument bigDoc = new XmlDocument();
bigDoc.LoadXml("<Request></Request>");

and I'm getting another XmlDocument that I want to insert inside <Request> node. It doesn't work for me:

 XmlNode requestNode =  bigDoc.FirstChild;
 requestNode.AppendChild(anotherXMLDocument);

It thorows an exception.

How can I insert a XmlDocument inside another XmlDocument node?

Answer

Kris picture Kris · Oct 6, 2010

If I recall correctly that it's basically the same thing in every DOM Implementation around (.net, javascript, php etc. this should work.

XmlNode requestNode =  bigDoc.FirstChild;
requestNode.AppendChild(
    requestNode.OwnerDocument.ImportNode(
        anotherXMLDocument.DocumentElement, true));

The true (2nd argument to importNode) should mean import deep.