2010-05-26 71 views
42

只是好奇爲什麼字典不支持XmlSerializer爲什麼XmlSerializer不支持Dictionary?

您可以通過使用DataContractSerializer和寫作對象的XmlTextWriter繞過它很輕鬆了,但什麼是一個字典,它使困難的XmlSerializer對付考慮它真的KeyValuePairs陣列的特性。

其實,你可以通過一個IDictionary<TKey, TItem>到期望的IEnumerable<KeyValuePairs<TKey, ITem>>的方法。

回答

27

Hashtable中需要哈希碼和相等比較器提供商通常。這些不能用XML很容易地序列化,並且絕對不會是可移植的。

但我想你已經找到了你的答案。只需將散列表序列化爲List<KeyValuePair<K,V>>,然後(重新)將其構建到散列表中。

+3

或使用代碼:http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx – prostynick 2010-05-26 09:30:51

+3

什麼方法/ Dictionary中的屬性暗示它必須作爲散列表來實現? Dictionary和IDictionary是Key/Value對的集合,與Hashtable實現不同。 從序列化的角度來看,我們的目標似乎是將數據從易失性存儲器中取出,以便能夠在稍後時間加載它。將任何*數據重新加載到接口的不同具體實現中將導致不同的行爲。 – Jeremy 2011-06-16 12:48:32

+0

序列化KeyValuePair不起作用。你最終會得到一個空標籤。請參閱:https://stackoverflow.com/questions/2658916/serializing-a-list-of-key-value-pairs-to-xml – NullAndVoid 2017-07-05 08:56:08

6

這是Waaay的遲到 - 但我發現這個問題,同時自己尋找答案,並認爲我會分享我的最終答案,即將XmlSerializer與不同的串行化方法分開。

http://www.sharpserializer.com

它爲我工作開箱的,連載字典,以及多層次的自定義類型,以及使用接口類型的參數,甚至遺傳學。也有完全許可的許可。

謝謝帕維爾睡姿!

+4

的DataContractSerializer將序列詞典,以及,現在是.NET Framework的一部分。 – 2012-03-16 18:11:55

1

您可以使用ExtendedXmlSerializer。 如果你有一個類:

public class TestClass 
{ 
    public Dictionary<int, string> Dictionary { get; set; } 
} 

,並創建該類的實例:

var obj = new TestClass 
{ 
    Dictionary = new Dictionary<int, string> 
    { 
     {1, "First"}, 
     {2, "Second"}, 
     {3, "Other"}, 
    } 
}; 

可以序列使用ExtendedXmlSerializer這個對象:

var serializer = new ConfigurationContainer() 
    .UseOptimizedNamespaces() //If you want to have all namespaces in root element 
    .Create(); 

var xml = serializer.Serialize(
    new XmlWriterSettings { Indent = true }, //If you want to formated xml 
    obj); 

輸出XML的樣子:

<?xml version="1.0" encoding="utf-8"?> 
<TestClass xmlns:sys="https://extendedxmlserializer.github.io/system" xmlns:exs="https://extendedxmlserializer.github.io/v2" xmlns="clr-namespace:ExtendedXmlSerializer.Samples;assembly=ExtendedXmlSerializer.Samples"> 
    <Dictionary> 
    <sys:Item> 
     <Key>1</Key> 
     <Value>First</Value> 
    </sys:Item> 
    <sys:Item> 
     <Key>2</Key> 
     <Value>Second</Value> 
    </sys:Item> 
    <sys:Item> 
     <Key>3</Key> 
     <Value>Other</Value> 
    </sys:Item> 
    </Dictionary> 
</TestClass> 

可以從nuget安裝ExtendedXmlSerializer或運行以下命令:

Install-Package ExtendedXmlSerializer