How to XML-serialize a dictionary

前端 未结 5 515
执笔经年
执笔经年 2020-11-29 07:16

I have been able to serialize an IEnumerable this way:

[XmlArray(\"TRANSACTIONS\")]
[XmlArrayItem(\"TRANSACTION\", typeof(Record))]
public IEnumerable

        
5条回答
  •  半阙折子戏
    2020-11-29 08:12

    Take a look at the following blog post

    • http://blogs.msdn.com/b/psheill/archive/2005/04/09/406823.aspx
    • http://web.archive.org/web/20100703052446/http://blogs.msdn.com/b/psheill/archive/2005/04/09/406823.aspx

    and this one (not in english, but the code is useful)

    • http://huseyint.com/2007/12/xml-serializable-generic-dictionary-tipi/

    Code sample from: http://web.archive.org/web/20100703052446/http://blogs.msdn.com/b/psheill/archive/2005/04/09/406823.aspx

    using System.Collections.Generic;
    using System.Collections;
    using System.IO;
    using System.Xml.Serialization;
    using System.Xml;
    using System;
    public static void Serialize(TextWriter writer, IDictionary dictionary)
    {
        List entries = new List(dictionary.Count);
        foreach (object key in dictionary.Keys)
        {
            entries.Add(new Entry(key, dictionary[key]));
        }
        XmlSerializer serializer = new XmlSerializer(typeof(List));
        serializer.Serialize(writer, entries);
    }
    public static void Deserialize(TextReader reader, IDictionary dictionary)
    {
        dictionary.Clear();
        XmlSerializer serializer = new XmlSerializer(typeof(List));
        List list = (List)serializer.Deserialize(reader);
        foreach (Entry entry in list)
        {
            dictionary[entry.Key] = entry.Value;
        }
    }
    public class Entry
    {
        public object Key;
        public object Value;
        public Entry()
        {
        }
    
        public Entry(object key, object value)
        {
            Key = key;
            Value = value;
        }
    }
    

    It generates output like the following, when the keys and values are strings.

    
    
      
        MyKey
        MyValue  
      
          
        MyOtherKey    
        MyOtherValue  
      
    
    

提交回复
热议问题