How to get replaced nodes in XDocument

I'm replacing nodes in XDocument, but I can't find a simple way to access them after they were replaced. In the code below I can replace "nodeC" with "newnode", but if I try to do something with the new node, it doesn't affect the document. How can I get the actually replaced nodes?

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. I can select them from the document afterwards, but I'd prefer to use something in API that will allow me to get the replaced elements.

Jon Skeet
people
quotationmark

The problem is that when you call Replace, newNode already has a parent - so it's cloned. If you remove it from its parent before calling ReplaceWith, then the element is added directly instead of a copy being added:

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

... now you'll see the comment in your document.

Another option (which doesn't affect the "source" document of the node) is to manually clone the node yourself instead:

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

Again, newNode now doesn't have a parent when you call ReplaceWith, so it doesn't need to be cloned again, and instead is inserted directly.

people

See more on this question at Stackoverflow