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.
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);
}
It looks like the ToString and reparse method is the best way. Here is the code:
XElement copy = XElement.Parse(original.ToString());