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中使用某些東西,這樣可以讓我獲得替換的元素。