[Serializable] [XmlRoot("Properties")] public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable, ISerializable { public SerializableDictionary() { } [EditorBrowsable(EditorBrowsableState.Advanced)] public SerializableDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { } [EditorBrowsable(EditorBrowsableState.Advanced)] [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { XmlSerializer xmlSerializer = typeof(TKey).CreateDefaultXmlSerializer(); XmlSerializer xmlSerializer2 = typeof(TValue).CreateDefaultXmlSerializer(); bool isEmptyElement = reader.IsEmptyElement; reader.Read(); if (!isEmptyElement) { while (reader.NodeType != XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); TKey key = (TKey)xmlSerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); TValue value = (TValue)xmlSerializer2.Deserialize(reader); reader.ReadEndElement(); base.Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } } public void WriteXml(XmlWriter writer) { XmlSerializer xmlSerializer = typeof(TKey).CreateDefaultXmlSerializer(); XmlSerializer xmlSerializer2 = typeof(TValue).CreateDefaultXmlSerializer(); foreach (TKey key in base.Keys) { writer.WriteStartElement("item"); writer.WriteStartElement("key"); xmlSerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement("value"); TValue val = base[key]; xmlSerializer2.Serialize(writer, val); writer.WriteEndElement(); writer.WriteEndElement(); } } }
public static T FromXmlString<T>(string xml) { if (string.IsNullOrEmpty(xml)) { return default(T); } using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml))) { return XmlObjectHelpers.FromXmlStream<T>(stream); } }
public static T DeserializeFromXml<T>(this string xml) { return XmlObjectHelpers.FromXmlString<T>(xml); }
代码来自:Kroll Software