XML serialization, deserialization, and XML serialization
XML serialization and deserialization using generics.
1. serialization
/// <Summary> /// serialize an object to string /// </summary> /// <typeparam name = "T"> Object Type </typeparam>/ // <param name = "o"> object to be serialized </param> // <returns> serialized string </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 ;}
2. deserialization
/// <Summary> /// deserialize string into an object /// </summary> /// <typeparam name = "T"> Object Type </typeparam> /// <param name = "xmlString"> string to be deserialized </param> // <returns> deserialized object </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 ;}