利用泛型實現XML的序列化與反序列化。
/// <summary> /// 將一個對象序列化為string /// </summary> /// <typeparam name="T">對象類型</typeparam> /// <param name="o">待序列化的對象</param> /// <returns>序列化後的字符串</returns> public static string ToXmlString<T>(T o) { XmlSerializer xs = new XmlSerializer(typeof(T)); XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces(); xmlns.Add(String.Empty, String.Empty); string result = string.Empty; using (StringWriter sw = new StringWriter()) { xs.Serialize(sw, o, xmlns); result = sw.ToString(); } return result; }
/// <summary> /// 將string反序列化為一個對象 /// </summary> /// <typeparam name="T">對象類型</typeparam> /// <param name="xmlString">待反序列化的字符串</param> /// <returns>反序列化後的對象</returns> public static T FromXmlString<T>(string xmlString) where T : class { T result = default(T); if (string.IsNullOrWhiteSpace(xmlString)) { return result; } XmlSerializer xs = new XmlSerializer(typeof(T)); using (StringReader sr = new StringReader(xmlString)) { result = xs.Deserialize(sr) as T; } return result; }