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

Daniel Plaisted picture Daniel Plaisted · Oct 16, 2008 · Viewed 20.3k times · Source

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.

Answer

Jonathan Moffatt picture Jonathan Moffatt · Dec 10, 2008

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);
}