2015-05-06 24 views
1

我正在替換XDocument中的節點,但我找不到在替換後訪問它們的簡單方法。在下面的代碼中,我可以用「newnode」替換「nodeC」,但是如果我嘗試對新節點進行操作,它不會影響文檔。我怎樣才能得到實際取代的節點?如何在XDocument中獲取替換的節點

var document = XDocument.Parse("<nodeA><nodeB/><nodeC/><nodeD/></nodeA>"); 
var oldNode = document.Descendants("nodeC").First(); 
var newNode = XElement.Parse("<root><newnode/></root>").Element("newnode"); 
oldNode.ReplaceWith(newNode); 
newNode.AddBeforeSelf(new XComment("comment")); // the comment is not added 

P.S.之後我可以從文檔中選擇它們,但我更喜歡在API中使用某些東西,這樣可以讓我獲得替換的元素。

回答

1

問題是,當您撥打Replace時,newNode已經有父母 - 所以它被克隆。如果您之前從其父刪除它調用ReplaceWith,則該元素被直接添加,而不是添加了一個副本:

newNode.Remove(); 
oldNode.ReplaceWith(newNode); 

...現在你會看到你的文檔中的註釋。

另一種選擇(這並不影響該節點的「源」文件)是自己手工克隆節點來代替:

newNode = new XElement(newNode); 
oldNode.ReplaceWith(newNode); 

再次,newNode現在沒有一個家長,當你調用ReplaceWith,所以不需要再次克隆,而是直接插入。