Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an independent copy of an XDocument?

I'm trying to create a new XDocument as follows:

var xmlString = _documentDictionary[documentKey].ToString(SaveOptions.DisableFormatting);

XDocument xml = XDocument.Parse(xmlString);

I now have xml which I would have though was a stand-alone instance of a document because I extracted the string from the original document and created a new one from that.

But when I modify xml and then inspect the _documentDictionary[documentKey] I can see that the original document has been modified also.

How can I get a new independent document from the existing collection that I have?

Note:

I've tried these but it doesn't work:

var xmlString = _documentDictionary[documentKey].ToString(SaveOptions.DisableFormatting);
var copyDoc = new XDocument(xmlString);

and

var copyDoc = new XDocument(_documentDictionary[documentKey]);
like image 519
DaveDev Avatar asked Apr 03 '13 08:04

DaveDev


2 Answers

There is a copy constructor defined for XDocument class:

var newDoc = new XDocument(xml);

You use this constructor to make a deep copy of an XDocument.

This constructor traverses all nodes and attributes in the document specified in the other parameter, and creates copies of all nodes as it assembles the newly initialized XDocument.

Quick test

var doc = new XDocument(new XElement("Test"));
var doc2 = new XDocument(doc);

doc.Root.Name = "Test2";

string name = doc.Root.Name.ToString();
string name2 = doc2.Root.Name.ToString();

name is "Test2" and name2 is "Test", what proofs that changes made on doc don't affect doc2.

like image 158
MarcinJuraszek Avatar answered Sep 25 '22 06:09

MarcinJuraszek


Try to copy constructor, like;

var newDoc = new XDocument(xml);

From MSDN:

You use this constructor to make a deep copy of an XDocument.

This constructor traverses all nodes and attributes in the document specified in the other parameter, and creates copies of all nodes as it assembles the newly initialized XDocument.

like image 32
Soner Gönül Avatar answered Sep 25 '22 06:09

Soner Gönül