How to XML-serialize a dictionary

c# serialize dictionary to json
serializabledictionary
xmlserializer dictionary
dotnet serialize dictionary
c# serialize dictionary values
c# serializabledictionary
c# serializable alternative to dictionary
vb net serialize a dictionary

I have been able to serialize an IEnumerable this way:

[XmlArray("TRANSACTIONS")]
[XmlArrayItem("TRANSACTION", typeof(Record))]
public IEnumerable<BudgetRecord> Records
{
    get 
    {
        foreach(Record br in _budget)
        {
            yield return br;
        }
    }
}

However, I realised that now I need a dictionary containing a collection Dictionary<string, RecordCollection> (RecordCollection implements IEnumerable).

How can I achieve that?


How to serialize/deserialize to `Dictionary<int, string>` from custom , To serialize the dictionary convert it to an instance of class A, and serialize KeyedCollection works like dictionary and is serializable. then create a class of type KeyedCollection, and define a property of your class as key. Usefull to serialize such type of datas. The reason why Dictionary<TKey, TValue> is not supported by the XmlSerializer is that types such as Dictionary, HashTable, etc. needs an equality comparer which can’t be serialized into XML easily and won’t be portable anyhow. To get around this problem, you generally have two options, in the order of my personal preference:


I have used the below for some time. It originally comes from here.

namespace SerializeDictionary
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;

    /// <summary>
    /// Represents an XML serializable collection of keys and values.
    /// </summary>
    /// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
    /// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
    [Serializable]
    [XmlRoot("dictionary")]
    public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
    {
        /// <summary>
        /// The default XML tag name for an item.
        /// </summary>
        private const string DefaultItemTag = "item";

        /// <summary>
        /// The default XML tag name for a key.
        /// </summary>
        private const string DefaultKeyTag = "key";

        /// <summary>
        /// The default XML tag name for a value.
        /// </summary>
        private const string DefaultValueTag = "value";

        /// <summary>
        /// The XML serializer for the key type.
        /// </summary>
        private static readonly XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));

        /// <summary>
        /// The XML serializer for the value type.
        /// </summary>
        private static readonly XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="SerializableDictionary&lt;TKey, TValue&gt;"/> class.
        /// </summary>
        public SerializableDictionary()
        {
        }

        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="SerializableDictionary&lt;TKey, TValue&gt;"/> class.
        /// </summary>
        /// <param name="info">A
        /// <see cref="T:System.Runtime.Serialization.SerializationInfo"/> object
        /// containing the information required to serialize the
        /// <see cref="T:System.Collections.Generic.Dictionary`2"/>.
        /// </param>
        /// <param name="context">A
        /// <see cref="T:System.Runtime.Serialization.StreamingContext"/> structure
        /// containing the source and destination of the serialized stream
        /// associated with the
        /// <see cref="T:System.Collections.Generic.Dictionary`2"/>.
        /// </param>
        protected SerializableDictionary(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }

        /// <summary>
        /// Gets the XML tag name for an item.
        /// </summary>
        protected virtual string ItemTagName
        {
            get
            {
                return DefaultItemTag;
            }
        }

        /// <summary>
        /// Gets the XML tag name for a key.
        /// </summary>
        protected virtual string KeyTagName
        {
            get
            {
                return DefaultKeyTag;
            }
        }

        /// <summary>
        /// Gets the XML tag name for a value.
        /// </summary>
        protected virtual string ValueTagName
        {
            get
            {
                return DefaultValueTag;
            }
        }

        /// <summary>
        /// Gets the XML schema for the XML serialization.
        /// </summary>
        /// <returns>An XML schema for the serialized object.</returns>
        public XmlSchema GetSchema()
        {
            return null;
        }

        /// <summary>
        /// Deserializes the object from XML.
        /// </summary>
        /// <param name="reader">The XML representation of the object.</param>
        public void ReadXml(XmlReader reader)
        {
            var wasEmpty = reader.IsEmptyElement;

            reader.Read();
            if (wasEmpty)
            {
                return;
            }

            try
            {
                while (reader.NodeType != XmlNodeType.EndElement)
                {
                    this.ReadItem(reader);
                    reader.MoveToContent();
                }
            }
            finally
            {
                reader.ReadEndElement();
            }
        }

        /// <summary>
        /// Serializes this instance to XML.
        /// </summary>
        /// <param name="writer">The XML writer to serialize to.</param>
        public void WriteXml(XmlWriter writer)
        {
            foreach (var keyValuePair in this)
            {
                this.WriteItem(writer, keyValuePair);
            }
        }

        /// <summary>
        /// Deserializes the dictionary item.
        /// </summary>
        /// <param name="reader">The XML representation of the object.</param>
        private void ReadItem(XmlReader reader)
        {
            reader.ReadStartElement(this.ItemTagName);
            try
            {
                this.Add(this.ReadKey(reader), this.ReadValue(reader));
            }
            finally
            {
                reader.ReadEndElement();
            }
        }

        /// <summary>
        /// Deserializes the dictionary item's key.
        /// </summary>
        /// <param name="reader">The XML representation of the object.</param>
        /// <returns>The dictionary item's key.</returns>
        private TKey ReadKey(XmlReader reader)
        {
            reader.ReadStartElement(this.KeyTagName);
            try
            {
                return (TKey)keySerializer.Deserialize(reader);
            }
            finally
            {
                reader.ReadEndElement();
            }
        }

        /// <summary>
        /// Deserializes the dictionary item's value.
        /// </summary>
        /// <param name="reader">The XML representation of the object.</param>
        /// <returns>The dictionary item's value.</returns>
        private TValue ReadValue(XmlReader reader)
        {
            reader.ReadStartElement(this.ValueTagName);
            try
            {
                return (TValue)valueSerializer.Deserialize(reader);
            }
            finally
            {
                reader.ReadEndElement();
            }
        }

        /// <summary>
        /// Serializes the dictionary item.
        /// </summary>
        /// <param name="writer">The XML writer to serialize to.</param>
        /// <param name="keyValuePair">The key/value pair.</param>
        private void WriteItem(XmlWriter writer, KeyValuePair<TKey, TValue> keyValuePair)
        {
            writer.WriteStartElement(this.ItemTagName);
            try
            {
                this.WriteKey(writer, keyValuePair.Key);
                this.WriteValue(writer, keyValuePair.Value);
            }
            finally
            {
                writer.WriteEndElement();
            }
        }

        /// <summary>
        /// Serializes the dictionary item's key.
        /// </summary>
        /// <param name="writer">The XML writer to serialize to.</param>
        /// <param name="key">The dictionary item's key.</param>
        private void WriteKey(XmlWriter writer, TKey key)
        {
            writer.WriteStartElement(this.KeyTagName);
            try
            {
                keySerializer.Serialize(writer, key);
            }
            finally
            {
                writer.WriteEndElement();
            }
        }

        /// <summary>
        /// Serializes the dictionary item's value.
        /// </summary>
        /// <param name="writer">The XML writer to serialize to.</param>
        /// <param name="value">The dictionary item's value.</param>
        private void WriteValue(XmlWriter writer, TValue value)
        {
            writer.WriteStartElement(this.ValueTagName);
            try
            {
                valueSerializer.Serialize(writer, value);
            }
            finally
            {
                writer.WriteEndElement();
            }
        }
    }
}

How to Serialize/Deserialize a Dictionary Object in C#, A developer gives a quick tutorial on how to work with serialization and deserialization of dictionary objects in C#, sharing all the necessary C#� The serialization and deserialization of .NET objects is made easy by using the various serializer classes that it provides. But serialization of a Dictionary object is not that easy.


Here's an even shorter version based on Gildors answer:

[XmlElement("Dictionary")]
public List<KeyValuePair<string, string>> XMLDictionaryProxy
{
    get
    {
        return new List<KeyValuePair<string, string>>(this.Dictionary);
    }
    set
    {
        this.Dictionary = new Dictionary<string, string>();
        foreach (var pair in value)
            this.Dictionary[pair.Key] = pair.Value;
    }
}

[XmlIgnore]
public Dictionary<string, string> Dictionary
{
    get; set;
}

Enjoy.

.Net Tips, “Cannot serialize member MyClass.MyDictionary of type System.Collections. Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0,� In my current situation I get an XML-file (format provided by me) and deserialize it to my class. I'm not fixed on a dictionary, any kind of data container was OK, holding all the attributes of one certain Element for further processing. So I get the XML-file with the given Element Structure (= my Class) but the Attributes of the elements could


Please try this alternative easy way:

void Main()
{
    var source=
        new TestClass() 
        { 
            GroupTestTyped=
                new Dictionary<string, int> { {"A", 23}, {"B", 40} }
        };
    using (var writer = XmlWriter.Create("c:\\test1.xml"))
        (new XmlSerializer(typeof(TestClass))).Serialize(writer, source);
}
[Serializable]
public class DemoElementClass
{
    public string Key { get; set; }
    public int Value { get; set; }  
}
[Serializable]
public class TestClass
{
   public TestClass() { }

   [XmlArray]
   [XmlArrayItem(ElementName = "ElementTest")]
   public List<DemoElementClass> GroupTest { get; set; }

   [XmlIgnore]
   public Dictionary<string, int> GroupTestTyped 
   {
       get { return GroupTest.ToDictionary(x=> x.Key, x => x.Value); }
       set { GroupTest = value.Select(x => new DemoElementClass {Key = x.Key, Value = x.Value}).ToList(); }
   }
}

Here the xml result:

<?xml version="1.0" encoding="utf-8"?>
<TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <GroupTest>
        <ElementTest>
            <Key>A</Key>
            <Value>23</Value>
        </ElementTest>
        <ElementTest>
            <Key>B</Key>
            <Value>40</Value>
        </ElementTest>
    </GroupTest>
</TestClass>

.Net Tips — Xml Serialize or Deserialize Dictionary in C#, If you try to serialize/deserialize a type which uses the generic Dictionary type with the XmlSerializer then you'll get an� The Serialize method is used to serialize an object to XML. Serialize is overloaded and can send output to a TextWriter , Stream , or XMLWriter object. In this example, you send the output to the console:


How to serialize dictionary object to XML file using c#, I have a dictionary object with all the values. Now, I wanted to serialize it into an xml file. Since dictionary is not supported with xmlserializer, I� 5 stars! I created a separate c# class and pasted this code in, I was able to use SerializableDictionary<string, string=""> as a parameter in my webmethod and it doesn't blow up my service as Dictionary<string, string=""> did. Thanks for taking the time to make this post!


Paul Welter's Weblog, XML Serializable Generic Dictionary For some reason, the generic Dictionary in . net 2.0 is not XML serializable. The following code snippet is a� There is a solution at Paul Welter's Weblog - XML Serializable Generic Dictionary. For some reason, the generic Dictionary in .net 2.0 is not XML serializable. The following code snippet is a xml serializable generic dictionary.


An Xml Serializable PropertyBag Dictionary Class for .NET, NET includes many Dictionary related types but serialization of Dictionaries leaves a lot to be desired. In this post I show how to create a� Just curious as to why Dictionary is not supported by XmlSerializer?. You can get around it easily enough by using DataContractSerializer and writing the object to a XmlTextWriter, but what are the characteristics of a Dictionary that makes it difficult for a XmlSerializer to deal with considering it's really an array of KeyValuePairs.