Customizes A serializable generic Dictionary <TKey, TValue> set, tkeytvalue
Dictionary is a collection of key-value types. It is a bit like an array, but the Dictionary key can be of any type. Internally, the Hash Table is used to store the key and value. This document defines a type-safe generic Dictionary <TKey, TValue> and can be serialized.
To enable custom generic Dictionary <TKey, TValue> to be serialized into xml, You need to implement the generic IXmlSerializable interface.
public class MySerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
// Key-based xml serializer
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
// Xml serializer of Values
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
// Judge whether the current node in xml is null
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
{
return;
}
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
// Read first key
reader.ReadStartElement("item");
reader.ReadStartElement("key");
// Deserialize to the key type
TKey key = (TKey) keySerializer.Deserialize(reader);
reader.ReadEndElement();
// Re-read value
reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
// Read the next node
reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
// Key-based xml serializer
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
// Xml serializer of Values
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();
}
}
}
The client uses XmlWriter to write the generic set Dictionary <TKey, TValue> into xml.
class Program
{
static void Main(string[] args)
{
MySerializableDictionary<int, string> mySerializableDictionary = new MySerializableDictionary<int, string>();
mySerializableDictionary.Add(1,"darren");
mySerializableDictionary.Add(2, "jack");
using (XmlWriter writer = XmlWriter.Create("infos.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("infos");
foreach (var item in mySerializableDictionary)
{
mySerializableDictionary.WriteXml(writer);
}
writer.WriteEndElement();
writer.WriteEndDocument();
}
Console. WriteLine ("xml written successfully ");
Console.ReadKey();
}
}
You can find the generated infos. xml file in the Debug folder.