PageRenderTime 102ms CodeModel.GetById 60ms app.highlight 5ms RepoModel.GetById 36ms app.codeStats 0ms

/WorldView/Structures/SerializableDictionary.cs

#
C# | 70 lines | 54 code | 15 blank | 1 comment | 3 complexity | d42385033385fd8e2f888b5973ef494c MD5 | raw file
 1// Credit to http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx
 2
 3using System;
 4using System.Collections.Generic;
 5using System.Xml.Serialization;
 6
 7[XmlRoot("dictionary")]
 8public class SerializableDictionary<TKey, TValue>
 9    : Dictionary<TKey, TValue>, IXmlSerializable
10{
11    #region IXmlSerializable Members
12    public System.Xml.Schema.XmlSchema GetSchema()
13    {
14        return null;
15    }
16
17    public void ReadXml(System.Xml.XmlReader reader)
18    {
19        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
20        XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
21
22        bool wasEmpty = reader.IsEmptyElement;
23        reader.Read();
24
25        if (wasEmpty)
26            return;
27
28        while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
29        {
30            reader.ReadStartElement("item");
31
32            reader.ReadStartElement("key");
33            TKey key = (TKey)keySerializer.Deserialize(reader);
34            reader.ReadEndElement();
35
36            reader.ReadStartElement("value");
37            TValue value = (TValue)valueSerializer.Deserialize(reader);
38            reader.ReadEndElement();
39
40            this.Add(key, value);
41
42            reader.ReadEndElement();
43            reader.MoveToContent();
44        }
45        reader.ReadEndElement();
46    }
47
48    public void WriteXml(System.Xml.XmlWriter writer)
49    {
50        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
51        XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
52
53        foreach (TKey key in this.Keys)
54        {
55            writer.WriteStartElement("item");
56
57            writer.WriteStartElement("key");
58            keySerializer.Serialize(writer, key);
59            writer.WriteEndElement();
60
61            writer.WriteStartElement("value");
62            TValue value = this[key];
63            valueSerializer.Serialize(writer, value);
64            writer.WriteEndElement();
65
66            writer.WriteEndElement();
67        }
68    }
69    #endregion
70}