SYSK 315: Generic Functions for Object ↔ XML Serialization/Deserialization

There are many reasons for custom serialization of an object into a human readable string (e.g. XML). If you find yourself recreating the serialization/deserialization code every few weeks, perhaps, it’s time to save off the functions below into a class in a shared assembly J.

public static string ToXml<T>(T source)

{

    string result = null;

    using (System.IO.StringWriter sw = new System.IO.StringWriter())

    {

        using (System.Xml.XmlWriter writer = System.Xml.XmlTextWriter.Create(sw, null))

        {

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

            serializer.Serialize(writer, source);

        }

        result = sw.ToString();

    }

    return result;

}

public static T FromXml<T>(string xml)

{

    T result = default(T);

    if (string.IsNullOrEmpty(xml) == false)

    {

        using (System.IO.StringReader sr = new System.IO.StringReader(xml))

        {

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

            result = (T) serializer.Deserialize(sr);

        }

    }

    return result;

}