Monday, August 8, 2011

Deep clone an XDocument

I’ve recently needed to clone an XDocument, and started looking in how to do this easy. The standard way to clone objects in .NET is by using the Clone method on a object implementing ICloneable, but XDocument doesn’t implement ICloneable. Now what to do?
I started my trusted browser, and the only way I found was to do this manually, and so I did. But I couldn’t let the thought go away, there had to be an easier way as cloning could be used a lot in LINQ.
I looked through the MSDN documentation, I sure enough I’ve found it, one of the constructors can do this, XDocument(XDocument). There is simply no reason to manual clone the document, and a constructor just like this exists for an XElement.
Many people may know this constructor exists, but I sure didn’t as it doesn’t following the “standard” .NET cloning methods. But the constructor way is much better, as we now are explicitly told whether or not the clone will be a shallow or deep clone.

Update: Added example as requested.

XmlDocument originalXml = new XmlDocument();
XmlDocument xmlCopy = new XmlDocument(originalXml);

4 comments:

  1. So can you post a code snippet on how to implement this?

    ReplyDelete
  2. Thanks for the example, but it should be XDocument, not XmlDocument.

    ReplyDelete
  3. Yeah, right XDocument. However, thanks very much! I didn't noticed that constructor in Intellisense, though i was looking for it.

    ReplyDelete