10/28/11

How to Clone XDocument

The XDocument class does not implement the ICloneable interface, so there is no Clone method to call. There is however a constructor that allow us to do this. The constructor takes an instance of XDocument and creates a new instance with the same XML structure. This can be done with the following code:

string xmlString = "<items><item/><item/></items>";
..

TextReader tr = new StringReader(xmlString);      
XDocument originalDoc = XDocument.Load(tr);
XDocument cloneDoc = new XDocument(originalDoc);

cloneDoc is a new instance that has the same XML document. Any changes to the cloneDoc does not affect the originalDoc XML document.

I hope this helps.