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;


}


 


Comments (3)

  1. Doug says:

    How fast do these methods run?

  2. irenake says:

    I don’t have any numbers at this time… But since it’s a very good question, I put it on my list of things to do — stay tuned, the answer will be posted in one of the upcoming blog posts in the next few days.