2 using System.Collections.Generic;
4 using System.Xml.Serialization;
8 [XmlRoot(
"dictionary")]
9 public class SerialisableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
11 #region IXmlSerializable Members
18 public void ReadXml(System.Xml.XmlReader reader)
20 XmlSerializer keySerializer =
new XmlSerializer(typeof(TKey));
21 XmlSerializer valueSerializer =
new XmlSerializer(typeof(TValue));
23 bool wasEmpty = reader.IsEmptyElement;
29 while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
31 reader.ReadStartElement(
"item");
32 reader.ReadStartElement(
"key");
33 TKey key = (TKey)keySerializer.Deserialize(reader);
34 reader.ReadEndElement();
35 reader.ReadStartElement(
"value");
36 TValue value = (TValue)valueSerializer.Deserialize(reader);
37 reader.ReadEndElement();
39 reader.ReadEndElement();
40 reader.MoveToContent();
42 reader.ReadEndElement();
45 public void WriteXml(System.Xml.XmlWriter writer)
47 XmlSerializer keySerializer =
new XmlSerializer(typeof(TKey));
48 XmlSerializer valueSerializer =
new XmlSerializer(typeof(TValue));
50 foreach (TKey key
in this.Keys)
52 writer.WriteStartElement(
"item");
53 writer.WriteStartElement(
"key");
54 keySerializer.Serialize(writer, key);
55 writer.WriteEndElement();
56 writer.WriteStartElement(
"value");
57 TValue value =
this[key];
58 valueSerializer.Serialize(writer, value);
59 writer.WriteEndElement();
60 writer.WriteEndElement();