Friday, 24 July 2015

Generic methods for xml serialization

Serialization XML
 
       public static string Serialize<T>(T param) where T:class
        {
            try
            {
                XmlSerializer ser = new XmlSerializer(typeof(T));
                StringWriter sw = new StringWriter();
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                ser.Serialize(sw, param, ns);
                return sw.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
 
Deserialization XML
 
        public static T Deserialize<T>(string xml) where T : class
        {
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
            try
            {
                XmlSerializer ser = new XmlSerializer(typeof(T));
                StreamReader sw = new StreamReader(stream);
                var dto = (T)ser.Deserialize(sw);
                return dto;
            }
            catch
            {
                return null;
            }
            finally
            {
                stream.Flush();
                stream.Dispose();
            }
        }

No comments:

Post a Comment