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]);
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With