My Technical Notes

Tuesday, 6 July 2010

XmlSerializer Helper class

A lot of the times, you will want to use C# in built XML (de-)serialization facilities in the exact same way: You begin with a object which you want to serialize and then you serialize it and then put the resulting string into the database, or alternatively you want to take an existing serialized object and deserialize to perform further actions with it.

The following class is a wrapper written specifically for this purpose. The contructor takes one or more type arguments (all of which may been to be serialized by this serializer) and then provides essentially two methods, one for serializing and one for deserializing. Additional overloads have been written for XElement because I am using LINQ To SQL which uses the XElement class to represent an XML column.


public class XmlSerializer
{
    System.Xml.Serialization.XmlSerializer serializer;

    public XmlSerializer(params Type[] types)
    {
        if (!types.Any()) throw new ArgumentException("specify at least one type", "types");
        var firstArg = types.First();
        var rest = types.Skip(1).ToArray();
        serializer = new System.Xml.Serialization.XmlSerializer(firstArg, rest);
    }

    public string SerializeToString(object o)
    {
        var writer = new StringWriter();
        serializer.Serialize(writer, o);
        return writer.ToString();
    }

    public XElement Serialize(object o)
    {
        return XElement.Parse(SerializeToString(o));
    }

    public object Deserialize(string serial)
    {
        StringReader reader = new StringReader(serial);
        return serializer.Deserialize(reader);
    }

    public object Deserialize(XElement serial)
    {
        return Deserialize(serial.ToString());
    }

    public T DeserializeTo<T>(string serial)
    {
        return (T)Deserialize(serial);
    }

    public T DeserializeTo<T>(XElement serial)
    {
        return (T)Deserialize(serial);
    }
}

No comments: