Namespace Tmac. Utilities { /// <Summary> /// Xml operation class /// </Summary> Public class XmlUtil { /// <Summary> /// Serialized object is xml (or byte stream) /// </Summary> /// <Param name = "obj"> </param> /// <Returns> </returns> Public static string XmlSerialize (object obj) { String result = null;
Try { XmlSerializer xmlSerializer = new XmlSerializer (obj. GetType ()); Using (MemoryStream stream = new MemoryStream ()) { XmlTextWriter xmlTextWriter = new XmlTextWriter (stream, new UTF8Encoding (false )); XmlTextWriter. Formatting = Formatting. Indented; XmlSerializer. Serialize (xmlTextWriter, obj ); XmlTextWriter. Flush (); XmlTextWriter. Close (); UTF8Encoding uTF8Encoding = new UTF8Encoding (false, true ); Result = uTF8Encoding. GetString (stream. ToArray ()); } } Catch (Exception ex) { Throw new Exception ("Couldn't serialize object:" + obj. GetType (). Name, ex ); } Return result; } /// <Summary> /// Reverse sequence xml is an object /// </Summary> /// <Typeparam name = "T"> </typeparam> /// <Param name = "type"> </param> /// <Param name = "xmlPath"> </param> /// <Returns> </returns> Public static T XmlDeserialize <T> (Type type, string xmlPath) { T obj = default (T ); XmlSerializer xmlSerializer = new XmlSerializer (type ); Try { Using (StreamReader sr = new StreamReader (xmlPath )) { Obj = (T) xmlSerializer. Deserialize (sr ); } } Catch (Exception ex) { Throw new Exception (String. Format ("Couldn't parse xml: {0}; Type: {1}", xmlPath, type. FullName), ex ); } Return obj; } } } |