Sunday, February 06, 2011

Annoyed by: System.Xml: The node to be inserted is from a different document context?


You try to copy one or more XML Nodes (usually elements though) from one XMLDocument and another, and you get the following error:

System.Xml: The node to be inserted is from a different document context.

My Fix, Hint:

(Note from 1/21/2012: Try using the XDocument class and LINQtoXML, it's much easier to deal with!)

There is an official way to fix this using clone, import and InsertBefore or After. But that's too difficult to figure out, in my case I still get the above mentioned exceptions. I often do not know which node to insert (you are supposed to find the parent node then insert) or afraid to insert something at a wrong node level.

Rather than wasting a whole lot of time, I do this entirely in text using StringBuilder and such. You will find the following methods very handy.


  • This contains the Text representation of XML including the node itself and all of the children.


  • This contains the Text representation of XML node of all its children.

You know that you can build up a string using StringBuilder.Append(string) you can form the basis for the new XML document which some of the node data copied from another XML document WITHOUT having any issues with copies being prohibited between two documents.

As an added bonus, you can see exactly the new XML document being formed since it is in the string form.

Once you form the destination XML, there is a handy function LoadXML(string), and you are back to have the new XMLDocument. There absolutely is no need to create a StringReader or stream of any kind.

XmlDocument xd = new XmlDocument();
var sx = sDoc.ToString();

Hope I gave you enough hint here, but if you need a more complete coding example, please post a comment and next time I come back here I will write one up for you.
Post a Comment