Search code examples
c#.netinsertxmldocumentxmlnode

insert XmlDocument into a XmlDocument node


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?


Solution

  • 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.