如何获得一个XDocument的独立副本? [英] How to get an independent copy of an XDocument?

查看:166
本文介绍了如何获得一个XDocument的独立副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个新的XDocument如下:

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

的XDocument XML = XDocument.Parse(的xmlString);



我现在有 XML 我将不得不虽然是一个文档的独立实例,因为我提取从原始文档字符串,并创建从一个新的。



但是,当我修改 XML ,然后检查 _documentDictionary [documentKey] 我可以看到原始文档也已修改。



我怎样才能从现有的集合一个新的独立的文件,我有



注意:



我试过这些,但它不工作:

  VAR的xmlString = _documentDictionary [documentKey]的ToString(SaveOptions.DisableFormatting); 
变种copyDoc =新的XDocument(的xmlString);

  VAR copyDoc =新的XDocument(_documentDictionary [documentKey]); 


解决方案

有一个的
的XDocument定义/msdn.microsoft.com/en-us/library/bb341301.aspx\">copy构造

  VAR newDoc =新的XDocument(XML); 




您使用此构造,使一个XDocument的深层副本。



这构造遍历所有节点,并在其他参数中指定的文件
属性,以及创建所有节点作为$ b $的副本b检查组装新初始化的XDocument。




快速测试

  VAR DOC =新的XDocument(新的XElement(测试)); 
变种DOC2 =新的XDocument(DOC);

doc.Root.Name =Test2的;

字符串名称= doc.Root.Name.ToString();
字符串名称2 = doc2.Root.Name.ToString();



名称 Test2的名2 测试,有什么证据,可以证明变化对<作出code>商务部不影响 DOC2


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.

这篇关于如何获得一个XDocument的独立副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆