錯誤資訊如下:
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/