Error: "The node to be inserted is from a different document context"

C#Xml

C# Problem Overview


When I am calling XmlNode.AppendChild(), I get this error:

> The node to be inserted is from a different document context.

static public XmlNode XMLNewChildNode(XmlNode oParent, string sName, 
    string sNamespaceURI, string sNodeType)
{
    XmlNode oNode = moDoc.CreateNode(sNodeType, sName, sNamespaceURI);
    oParent.AppendChild(oNode);
    return oNode;
}

This code was converted from its VB 6.0 version which was this (please ignore the optional parameters, I have overloads for them in C# version):

Public Function XMLNewChildNode(ByVal oParent As IXMLDOMNode, ByVal _
    sName As String, Optional ByVal sNamespaceURI As String = "", _
    Optional ByVal sNodeType As String = "element") As IXMLDOMNode
'**************** DESCRIPTION *******************
  'Create a new Child Node for passed Parent.
'***************** VARIABLES ********************
  Dim oNode As IXMLDOMNode
'************************************************
  Set oNode = moDoc.createNode(sNodeType, sName, sNamespaceURI)
  Call oParent.appendChild(oNode)
  Set XMLNewChildNode = oNode
End Function

Why does the VB code work while the C# does not? Are there differences between how VB and C# handle XML, that I need to be aware of?

C# Solutions


Solution 1 - C#

You need to import the node into the document before appending it:

XmlNode oNode = moDoc.CreateNode(sNodeType, sName, sNamespaceURI);

//necessary for crossing XmlDocument contexts
XmlNode importNode = oParent.OwnerDocument.ImportNode(oNode, true);

oParent.AppendChild(importNode);
return oNode;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBohnView Question on Stackoverflow
Solution 1 - C#Rex MView Answer on Stackoverflow