1 /// <summary>
2 /// 支持XML序列化的泛型 Dictionary
3 /// </summary>
4 /// <typeparam name="TKey"></typeparam>
5 /// <typeparam name="TValue"></typeparam>
6 [XmlRoot("dictionary")]
7 public class SerializableDictionary<TKey, TValue>
8 : Dictionary<TKey, TValue>, IXmlSerializable
9 {
10
#region 构造函数
public
SerializableDictionary():base()
{
}
public
SerializableDictionary(IDictionary<TKey, TValue>
dictionary):base(dictionary)
{
}
public SerializableDictionary(IEqualityComparer<TKey>
comparer):base(comparer)
{
}
public
SerializableDictionary(int capacity):base(capacity)
{
}
public
SerializableDictionary(int capacity, IEqualityComparer<TKey>
comparer)
:base(capacity,comparer)
{
}
protected
SerializableDictionary(SerializationInfo info, StreamingContext
context):base(info,context)
{
}
#endregion
11 #region IXmlSerializable Members
12 public System.Xml.Schema.XmlSchema GetSchema()
13 {
14 return null;
15 }
16
17 /// <summary>
18 /// 从对象的 XML 表示形式生成该对象
19 /// </summary>
20 /// <param name="reader"></param>
21 public void ReadXml(System.Xml.XmlReader reader)
22 {
23
24 XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
25 XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
26 bool wasEmpty = reader.IsEmptyElement;
27 reader.Read();
28
29 if (wasEmpty)
30 return;
31 while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
32 {
33 reader.ReadStartElement("item");
34 reader.ReadStartElement("key");
35 TKey key = (TKey)keySerializer.Deserialize(reader);
36 reader.ReadEndElement();
37 reader.ReadStartElement("value");
38 TValue value = (TValue)valueSerializer.Deserialize(reader);
39 reader.ReadEndElement();
40 this.Add(key, value);
41 reader.ReadEndElement();
42 reader.MoveToContent();
43
44 }
45 reader.ReadEndElement();
46
47 }
48
49
50 /// <summary>
51 /// 将对象转换为其 XML 表示形式
52 /// </summary>
53 /// <param name="writer"></param>
54 public void WriteXml(System.Xml.XmlWriter writer)
55 {
56
57 XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
58 XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
59 foreach (TKey key in this.Keys)
60 {
61 writer.WriteStartElement("item");
62 writer.WriteStartElement("key");
63 keySerializer.Serialize(writer, key);
64 writer.WriteEndElement();
65 writer.WriteStartElement("value");
66 TValue value = this[key];
67 valueSerializer.Serialize(writer, value);
68 writer.WriteEndElement();
69 writer.WriteEndElement();
70 }
71
72 }
73
74 #endregion
75
76 }