Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...