Original: http://www.aspcode.net/The-node-to-be-inserted-is-from-a-different-document-context.aspx
Soon after I recommended my (just published solution) for merging XML files for a person I know he contacted me and said he was getting the error "The node to be inserted is from a different document context ".
After some investigating it turned out he had not copied the solution by using the clipboad function, but rather typing it in - and missed the oh so important oDocFirst.ImportNode call.
I.e he was using code like:
XmlNode oNodeWhereInsert = oDocFirst.SelectSingleNode("/rss/channel");
foreach( XmlNode oNode in oDocSecond.SelectNodes("/rss/channel/item"))
{
oNodeWhereInsert.AppendChild(oNode.Clone());
}
instead of
XmlNode oNodeWhereInsert = oDocFirst.SelectSingleNode("/rss/channel");
foreach( XmlNode oNode in oDocSecond.SelectNodes("/rss/channel/item"))
{
oNodeWhereInsert.AppendChild(oDocFirst.ImportNode(oNode,true));
}
PunCha注: 在被拷贝的节点来自于其他XmlDocument是,可以使用XmlDocument.ImportNode来导入节点。