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

标签 c# xml

当我调用 XmlNode.AppendChild() 时,出现此错误:

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;
}

此代码是从它的 VB 6.0 版本转换而来的(请忽略可选参数,我在 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

为什么 VB 代码可以工作而 C# 不能? VB 和 C# 处理 XML 的方式是否存在我需要注意的差异?

最佳答案

您需要在附加节点之前将节点导入到文档中:

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

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

oParent.AppendChild(importNode);
return oNode;

关于c# - 错误 : "The node to be inserted is from a different document context",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3019136/

相关文章:

c# - 警告尝试构建 Service Fabric AspNetCore2 项目

c# - 检查事件是否有任何监听器?

android - Material 组件底部导航 View

java - JAXB 解码返回属性的 null

java - 使用 java 在 XML 中添加新节点

c# - 在 C# 中将泛型委托(delegate)作为方法参数传递

c# - 在 C++ 中使用 C# 嵌套结构

c# - 使用可选参数对象注册 autofac 组件

android - 每个 ImageView 都需要 CardView 吗?

xml - 折叠箭头列表