SECI  1
 All Classes Namespaces Files Functions Variables Enumerations Enumerator Properties Events
SerialisableDictionary.cs
Go to the documentation of this file.
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Xml.Serialization;
5 
6 namespace Seci.Tools
7 {
8  [XmlRoot("dictionary")]
9  public class SerialisableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
10  {
11  #region IXmlSerializable Members
12 
13  public System.Xml.Schema.XmlSchema GetSchema()
14  {
15  return null;
16  }
17 
18  public void ReadXml(System.Xml.XmlReader reader)
19  {
20  XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
21  XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
22 
23  bool wasEmpty = reader.IsEmptyElement;
24  reader.Read();
25 
26  if (wasEmpty)
27  return;
28 
29  while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
30  {
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();
38  this.Add(key, value);
39  reader.ReadEndElement();
40  reader.MoveToContent();
41  }
42  reader.ReadEndElement();
43  }
44 
45  public void WriteXml(System.Xml.XmlWriter writer)
46  {
47  XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
48  XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
49 
50  foreach (TKey key in this.Keys)
51  {
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();
61  }
62  }
63 
64  #endregion
65 
66  }
67 }