XML Serializable Generic Dictionary
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. The dictionary is serialable by implementing the IXmlSerializable interface.
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Xml. Serialization;
[XmlRoot ("dictionary")]
Public class SerializableDictionary <TKey, TValue>
: Dictionary <TKey, TValue>, IXmlSerializable
{
# Region IXmlSerializable Members
Public System. Xml. Schema. XmlSchema GetSchema ()
{
Return null;
}
Public void ReadXml (System. Xml. XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer (typeof (TKey ));
XmlSerializer valueSerializer = new XmlSerializer (typeof (TValue ));
Bool wasEmpty = reader. IsEmptyElement;
Reader. Read ();
If (wasEmpty)
Return;
While (reader. NodeType! = System. Xml. 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 ();
This. Add (key, value );
Reader. ReadEndElement ();
Reader. MoveToContent ();
}
Reader. ReadEndElement ();
}
Public void WriteXml (System. Xml. XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer (typeof (TKey ));
XmlSerializer valueSerializer = new XmlSerializer (typeof (TValue ));
Foreach (TKey key in this. Keys)
{
Writer. WriteStartElement ("item ");
Writer. WriteStartElement ("key ");
KeySerializer. Serialize (writer, key );
Writer. WriteEndElement ();
Writer. WriteStartElement ("value ");
TValue value = this [key];
ValueSerializer. Serialize (writer, value );
Writer. WriteEndElement ();
Writer. WriteEndElement ();
}
}
# Endregion
}
From strayromeo