tags:

views:

63

answers:

1

When I am Calling 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 is a code that is converted from its VB 6.0 version which was this: please ignore the optional parametes, 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

so anything is different in VB 6.0 and C# for working with XMLs?

+2  A: 

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;
Rex M
Thanks Sir! ImportNode takes two params... the second one is for deepClone ... How can I decide if I should pass True or False to it?
BDotA
@BDotA true if you want to import the node and all its children; false if you just want to import the top-level node.
Rex M
thanks ... I tried both true and false and I am getting Null Ref Exception on the ImportNode line... is it still something with my XML codes? or this one is related to the data that I am passing ?
BDotA
@BDotA debug and figure out which object is null
Rex M