1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Xml.Serialization; 6 using System.Xml; 7 using System.Xml.Schema; 8 using System.Runtime.Serialization; 9 10 /// <summary> 11 /// 标题:支持 XML 序列化的 Dictionary 12 /// </summary> 13 /// <typeparam name="TKey"></typeparam> 14 /// <typeparam name="TValue"></typeparam> 15 [XmlRoot("SerializableDictionary")] 16 public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable 17 { 18 19 public SerializableDictionary() 20 : base() 21 { 22 } 23 public SerializableDictionary(IDictionary<TKey, TValue> dictionary) 24 : base(dictionary) 25 { 26 } 27 28 public SerializableDictionary(IEqualityComparer<TKey> comparer) 29 : base(comparer) 30 { 31 } 32 33 public SerializableDictionary(int capacity) 34 : base(capacity) 35 { 36 } 37 public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer) 38 : base(capacity, comparer) 39 { 40 } 41 protected SerializableDictionary(SerializationInfo info, StreamingContext context) 42 : base(info, context) 43 { 44 } 45 46 47 public System.Xml.Schema.XmlSchema GetSchema() 48 { 49 return null; 50 } 51 /// <summary> 52 /// 从对象的 XML 表示形式生成该对象 53 /// </summary> 54 /// <param name="reader"></param> 55 public void ReadXml(System.Xml.XmlReader reader) 56 { 57 XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); 58 XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); 59 bool wasEmpty = reader.IsEmptyElement; 60 reader.Read(); 61 if (wasEmpty) 62 return; 63 while (reader.NodeType != System.Xml.XmlNodeType.EndElement) 64 { 65 reader.ReadStartElement("item"); 66 reader.ReadStartElement("key"); 67 TKey key = (TKey)keySerializer.Deserialize(reader); 68 reader.ReadEndElement(); 69 reader.ReadStartElement("value"); 70 TValue value = (TValue)valueSerializer.Deserialize(reader); 71 reader.ReadEndElement(); 72 this.Add(key, value); 73 reader.ReadEndElement(); 74 reader.MoveToContent(); 75 } 76 reader.ReadEndElement(); 77 } 78 79 /**/ 80 /// <summary> 81 /// 将对象转换为其 XML 表示形式 82 /// </summary> 83 /// <param name="writer"></param> 84 public void WriteXml(System.Xml.XmlWriter writer) 85 { 86 XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); 87 XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); 88 foreach (TKey key in this.Keys) 89 { 90 writer.WriteStartElement("item"); 91 writer.WriteStartElement("key"); 92 keySerializer.Serialize(writer, key); 93 writer.WriteEndElement(); 94 writer.WriteStartElement("value"); 95 TValue value = this[key]; 96 valueSerializer.Serialize(writer, value); 97 writer.WriteEndElement(); 98 writer.WriteEndElement(); 99 } 100 } 101 102 }