一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

dom XML文档元素互相复制解决方法

时间:2011-11-14 编辑:简简单单 来源:一聚教程网

错误信息如下:
The node to be inserted is from a different document context
意思是不能直接插入其他xml文档中的元素。解决方法是用ImportNode();函数先导出。XmlDocument xmlOld = new
今天在使用XML节点复制时,遇到一些问题,浪费了2个小时的时间。可是,公司的网络又慢,只能通过MSN请朋友帮我根据错误信息找。还好,找到了解决问题的方法。

 代码如下 复制代码
XmlDocument();//老文档
XmlNode nodeOld = xmlOld.SelectSingleNode("xpath");//老文档中元素
XmlDocument xmlNew = new XmlDocument();//新文档
XmlNode nodeNew = xmlNew.ImportNode(nodeOld, true);//先导入老文档中的元素
xmlNew.AppendChild(nodeNew);//再追加
xmlNew.AppendChild(nodeOld);//

这样会提示那样的错误信息下面是一些可能有用的信息:

错误信息如下:
The   node   to   be   inserted   is   from   a   different   document   context

我测试了Clone/CloneNode两个方法,同样出现这个错误。


根据文档的说明,使用ImportNode解决了问题。

有经验的朋友,讲讲为什么?
-----------------------------------------------------------------------------------------------------
这是英文的帖子:

 代码如下 复制代码

Hi,

I 've   got   the   following   piece   of   code   that 's   causing   me   a   bit   of   a   problem

XmlDocument   doc     =   new   XmlDocument   ();
XmlNode   rootNode   =   doc.CreateNode   (XmlNodeType.Element,   "usersettings ",
null);
User   user     =   new   User   (userid);
XmlNode   rolesNode   =   user.GetRoles   ();
rootNode.AppendChild   (rolesNode);
                                      :
                                      :

The   last   line   (rootNode.AppendChild   (rolesNode))   throws   an   exception   "The
node   to   be   inserted   is   from   a   different   document   context. "   How   can   I   work
around   this?   The   code   above   is   from   a   Web-service   that   collects   various
information   regarding   a   user   from   different   sources   each   of   which   returns   an
XmlNode.   The   web-service   adds   each   XmlNode   to   a   "root "   node   and   then   returns
this   "root "   node   to   the   client.

Eirik   M.


网友的回复:

 代码如下 复制代码

The   proble   you 're   having   relates   to   the   fact   that   the   user   object   is
creating   a   node   from   othe   document,   rather   than   from   doc.

Either   you   pass   doc   to   GetRoles   so   that   the   nodes   are   created   from   the
correct   instance,   or   you   may   have   to   use   ImportNode

rootNode.AppendChild(doc.ImportNode(rolesNode,true));

instead   of   the   previous   AppendChild.

best   regards
ricardo 


-------------------------------------------------------------------------------------------------------


在.NET里,一个节点是有context   的,只能属于一个XML文档,你可以看到XmlNode有个只读OwnerDocument属性,这是跟w3c的标准相符合的

如果你需要把一个节点拷贝到另一个文档去,需要使用ImportNode

参考
http://msdn.microsoft.com/msdnmag/issues/02/05/web/

热门栏目