Error: "the node to be inserted is associated with a different document context"

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

The inserted node refers to 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 VB 6.0, which was like this (please ignore the optional parameters, I have overloads for them in C #):

 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 VB code work while C # doesn't work? Are there any differences between how VB and C # process XML, which should I be aware of?

+85
c # xml
Jun 10 '10 at
source share
1 answer

You need to import the node into the document before adding 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; 
+162
Jun 10 '10 at 23:18
source share



All Articles