Tuesday, 9 May 2017

C# Generic function to desirialize XML into c# class.


public static T ParseXML<T>(string xml)
        {
            Type type = typeof(T);
            var obj = Activator.CreateInstance(type);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            using (StringReader reader = new StringReader(doc.InnerXml))
            {
                obj = (T)(serializer.Deserialize(reader));
            }

            return (T)obj;
        }

No comments:

Post a Comment