XML serialization for Dictionary generic

For some reasons Microsoft made their generic Dictionary<TKey, TValue> class not XML-serializable. But making your own Dictionary that supports XML serialization is very simple. All you have to do is to write an implementation of IXmlSerializable interface.

namespace OXT.Utils
{
	[XmlRoot("dictionary")]
	public class SerializableDictionary<TKey, TValue>; : Dictionary<TKey, TValue>, IXmlSerializable
	{
		#region IXmlSerializable Members
 
		public XmlSchema GetSchema()
		{
			return null;
		}
 
		public void ReadXml(XmlReader reader)
		{
			XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
			XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
 
			// element is empty
			if (reader.IsEmptyElement)
			{
				reader.Read();
				return;
			}
 
			// reading initial element
			reader.Read();
			while (reader.NodeType != XmlNodeType.EndElement)
			{
				reader.ReadStartElement("item");
 
				reader.ReadStartElement("key");
				TKey key = (TKey)keySerializer.Deserialize(reader);
				reader.ReadEndElement();
 
				reader.ReadStartElement("value");
				TValue value = (TValue)valueSerializer.Deserialize(reader);
				reader.ReadEndElement();
 
				Add(key, value);
 
				reader.ReadEndElement();
				reader.MoveToContent();
			}
 
			reader.ReadEndElement();
		}
 
		public void WriteXml(XmlWriter writer)
		{
			XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
			XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
 
			foreach (TKey key in Keys)
			{
				writer.WriteStartElement("item");
 
				writer.WriteStartElement("key");
				keySerializer.Serialize(writer, key);
				writer.WriteEndElement();
 
				writer.WriteStartElement("value");
				valueSerializer.Serialize(writer, this[key]);
				writer.WriteEndElement();
 
				writer.WriteEndElement();
			}
		}
 
		#endregion
	}
 
}

Tags: , , ,

AddThis Social Bookmark Button

Leave a Reply