当我致电XmlNode.AppendChild()
时,我收到此错误:
要插入的节点来自不同的文档上下文。
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之间是否存在差异,我需要注意哪些?
答案 0 :(得分:182)
您需要在添加节点之前将节点导入到文档中:
XmlNode oNode = moDoc.CreateNode(sNodeType, sName, sNamespaceURI);
//necessary for crossing XmlDocument contexts
XmlNode importNode = oParent.OwnerDocument.ImportNode(oNode, true);
oParent.AppendChild(importNode);
return oNode;