How to get an independent copy of an XDocument?

2019-06-15 19:51发布

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

2条回答
相关推荐>>
2楼-- · 2019-06-15 20:51

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.

查看更多
Deceive 欺骗
3楼-- · 2019-06-15 20:54

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.

查看更多
登录 后发表回答