2015-02-08 19 views
0

我正在編寫一個Windows應用商店應用,它涉及將Xml文件序列化到字典中,反之亦然。隨着名單<>和的ObservableCollection <>,我可以做到這一點從XML文件中讀取: 詞類c#將字典序列化爲xml文件

public class word 
{ 
    [XmlElement("key")] 
    public string words { get; set; } 
    [XmlElement("value")] 
    public string value { get; set; } 
} 

using System.IO; 
using Windows.Storage; 
using System.Xml.Serialization; 
using System.Collections.ObjectModel; 

ObservableCollection<word> Words = new ObservableCollection<word>; 
    public async void Load() 
     { 
      StorageFolder localFolder = Windows.Storage.KnownFolders.MusicLibrary; 
      StorageFile file = await localFolder.GetFileAsync("dictionary.xml"); 
      XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<word>)); 
      using (Stream stream = await file.OpenStreamForReadAsync()) 
      { 
       ObservableCollection<word> list = serializer.Deserialize(stream) as ObservableCollection<word>; 
       foreach (var c in list) 
       { 
        Words.Add(c); 
       } 
      } 
     } 

但是字典<>有一對TKEY的和TValue的,這使得上面的代碼無法使用。無論如何修復上面的代碼適用於詞典<>?任何幫助表示感謝。

回答

0

您需要將每個項目轉換爲不是KeyValuePair的對象。我使用這樣一個簡單的類來序列化一個Dictionary,它可以很容易地被修改爲支持ConcurrentDictionay或ObservableCollection。

static public class XmlDictionarySerializer<A, B> 
{ 
    public class Item 
    { 
     public A Key { get; set; } 
     public B Value { get; set; } 
    } 

    static public void Serialize(IDictionary<A, B> dictionary, string filePath) 
    { 
     List<Item> itemList = new List<Item>(); 
     foreach (A key in dictionary.Keys) 
     { 
      itemList.Add(new Item() { Key = key, Value = dictionary[key] }); 
     } 

     XmlDataSerializer.Serialize<List<Item>>(itemList, filePath); 
    } 

    static public Dictionary<A, B> DeserializeDictionary(string filePath) 
    { 
     Dictionary<A, B> dictionary = new Dictionary<A, B>(); 
     List<Item> itemList = XmlDataSerializer.Deserialize<List<Item>>(filePath); 
     foreach (Item item in itemList) 
     { 
      dictionary.Add(item.Key, item.Value); 
     } 
     return dictionary; 
    } 
}