Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a deep copy of an element in LINQ to XML?

I want to make a deep copy of a LINQ to XML XElement. The reason I want to do this is there are some nodes in the document that I want to create modified copies of (in the same document). I don't see a method to do this.

I could convert the element to an XML string and then reparse it, but I'm wondering if there's a better way.

like image 269
Daniel Plaisted Avatar asked Oct 16 '08 17:10

Daniel Plaisted


2 Answers

There is no need to reparse. One of the constructors of XElement takes another XElement and makes a deep copy of it:

XElement original = new XElement("original"); XElement deepCopy = new XElement(original); 

Here are a couple of unit tests to demonstrate:

[TestMethod] public void XElementShallowCopyShouldOnlyCopyReference() {     XElement original = new XElement("original");     XElement shallowCopy = original;     shallowCopy.Name = "copy";     Assert.AreEqual("copy", original.Name); }  [TestMethod] public void ShouldGetXElementDeepCopyUsingConstructorArgument() {     XElement original = new XElement("original");     XElement deepCopy = new XElement(original);     deepCopy.Name = "copy";     Assert.AreEqual("original", original.Name);     Assert.AreEqual("copy", deepCopy.Name); } 
like image 157
Jonathan Moffatt Avatar answered Oct 07 '22 00:10

Jonathan Moffatt


It looks like the ToString and reparse method is the best way. Here is the code:

XElement copy = XElement.Parse(original.ToString()); 
like image 43
Daniel Plaisted Avatar answered Oct 07 '22 00:10

Daniel Plaisted