c#将字典序列化为xml文件

时间:2015-02-08 16:35:03

标签: c# dictionary windows-store-apps

我正在编写Windows应用商店应用,其中涉及将Xml文件序列化为字典,反之亦然。使用List<>和ObservableCollection<>,我可以这样做从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);
                }
            }
        }

但是词典&lt;&gt;有一对TKey和TValue,使上面的代码无法使用。无论如何要修复上面的代码以适合Dictionary&lt;&gt;?任何帮助都是值得赞赏的。

1 个答案:

答案 0 :(得分: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;
    }
}