Last XML serializer I’ll ever write


I’ve made this class probably a half dozen times, and I’m getting pretty tired of writing it.  It seems like every application I write has to serialize and deserialize back and forth between XML strings and objects.  For future reference, here it is:

public static class XmlSerializationHelper
{
    public static string Serialize<T>(T value)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringWriter writer = new StringWriter();
        xmlSerializer.Serialize(writer, value);

        return writer.ToString();
    }

    public static T Deserialize<T>(string rawValue)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringReader reader = new StringReader(rawValue);

        T value = (T)xmlSerializer.Deserialize(reader);
        return value;
    }
}

I like this implementation as it’s generic so it removes some casting from the user.  Yeah, I know this code is probably in a hundred other blogs.  But at least now I know exactly where to find it.

Unit testing MonoRail controllers – Redirects