PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 0ms 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. using System;
  3. using System.Collections.Generic;
  4. using System.Xml.Serialization;
  5. [XmlRoot("dictionary")]
  6. public class SerializableDictionary<TKey, TValue>
  7. : Dictionary<TKey, TValue>, IXmlSerializable
  8. {
  9. #region IXmlSerializable Members
  10. public System.Xml.Schema.XmlSchema GetSchema()
  11. {
  12. return null;
  13. }
  14. public void ReadXml(System.Xml.XmlReader reader)
  15. {
  16. XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
  17. XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
  18. bool wasEmpty = reader.IsEmptyElement;
  19. reader.Read();
  20. if (wasEmpty)
  21. return;
  22. while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
  23. {
  24. reader.ReadStartElement("item");
  25. reader.ReadStartElement("key");
  26. TKey key = (TKey)keySerializer.Deserialize(reader);
  27. reader.ReadEndElement();
  28. reader.ReadStartElement("value");
  29. TValue value = (TValue)valueSerializer.Deserialize(reader);
  30. reader.ReadEndElement();
  31. this.Add(key, value);
  32. reader.ReadEndElement();
  33. reader.MoveToContent();
  34. }
  35. reader.ReadEndElement();
  36. }
  37. public void WriteXml(System.Xml.XmlWriter writer)
  38. {
  39. XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
  40. XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
  41. foreach (TKey key in this.Keys)
  42. {
  43. writer.WriteStartElement("item");
  44. writer.WriteStartElement("key");
  45. keySerializer.Serialize(writer, key);
  46. writer.WriteEndElement();
  47. writer.WriteStartElement("value");
  48. TValue value = this[key];
  49. valueSerializer.Serialize(writer, value);
  50. writer.WriteEndElement();
  51. writer.WriteEndElement();
  52. }
  53. }
  54. #endregion
  55. }