简体   繁体   中英

c# serialize dictionary into xml file

I'm writing an Windows Store App which involve serializing Xml file into a dictionary and vice versa. With List<> and ObservableCollection<>, I can do this to read from XML file: Word Class

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

Read Class

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);
                }
            }
        }

But Dictionary<> has a pair of TKey and TValue, which make the code above unusable. Anyway to fix the above code to be suitable for Dictionary<>? Any help is appreciate.

You need to convert each item to an object that is not a KeyValuePair. I use a simple class like this to serialize a Dictionary, which could easliy be modified to support a ConcurrentDictionay or 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM