[英]Deep Copy of XDocument/Element with associated XElement (s)
好的,我有一個XDocument
BaseDocument = XDocument.Load(@".\Example\Template.xml");
以及通過方法生成的XElement的一些DataStructure(在XDocument內部)。 這只是一個例子:
Dictionary<string, List<XElement>> ElementMap = GetElementMapping(BaseDocument);
我想同時復制兩者,
有沒有比這更有效的方法,
XDocument copy = new XDocument(BaseDocument);
Dictionary<string, List<XElement>> copyElementMap = GetElementMapping(copy);
復制數據結構,以便內部的XElements引用新副本?
我做了一些圖片來展示我想要的東西:
當前解決方案:
智能解決方案:
就您制作的XDocument副本而言,我們可以肯定的是, 正如我們從第2320行的文檔中可以看到的那樣 ,它肯定會盡可能地快。 這確實復制了我們想要的方式。
如果您需要對XDocument對象進行深層復制,那么以上是關於性能的最佳方法。 它無需重新加載文件即可對文檔中的每個節點(包括XElement,XAttributes,注釋等)執行深層復制。 它在內存中讀取並克隆所有節點。 這是一種高效的操作,也是我們所能獲得的最高效的操作,因為它會自動禁止通常在XDocument內部觸發的所有通知事件。 可以從以下方式驗證深層副本:
使用的XML:
<?xml version="1.0" encoding="utf-8" ?>
<FirstNode>
<ChildNode attributeOne="1"/>
</FirstNode>
源代碼
XDocument xDoc = XDocument.Load("AnXml.xml");
XDocument copy = new XDocument(xDoc);
Console.WriteLine("xDoc before change copy: {0}", xDoc.ToString());
copy.Root.Add(new XElement("NewElement", 5));
copy.Element("FirstNode").Element("ChildNode").Attribute("attributeOne").SetValue(2);
Console.WriteLine("xDoc after change copy: {0}", xDoc.ToString());
Console.WriteLine("copy after change copy: {0}", copy.ToString());
Console.ReadKey();
對Console.WriteLine的兩次調用輸出不同的值,指示兩個引用指向具有不同結構的不同項,從而證明已進行了深拷貝。
請注意,如果要重復使用現有的XElement,則無法在不使用反射的情況下將它們設置到XDocument中:在XDocument中設置XElement的所有公共方法都將執行深層復制。 從我包含的鏈接(.Net源代碼)可以明顯看出這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.