August 10, 2008

Xml Serialisation/Deserialisation

A simple helper class
using System.Xml.Serialization;

...
public static class XmlSerializationHelper
{

    // Serialize the given type (only reference types) to an Xml string
    // Catches any exceptions
    // Eg:
    // string xmlString = SerializationHelper.SerializeToXml<MyClass>(myClass);      
    public static string TrySerializeToXml<T>(this T targetObj, params Type[] extraTypes)
        where T : class // (only reference types)
    {
        string res = string.Empty;
        try
        {
            StringBuilder builder = new StringBuilder();
            XmlSerializer xmlSerializer = new XmlSerializer(typeof (T), extraTypes);
            xmlSerializer.Serialize(new StringWriter(builder), targetObj);
            res = builder.ToString();
        }
        catch (Exception ex)
        {
            Trace.WriteLine("SerializationHelper.SerializeToXml<T>: " +
                            "Exception occurred during deserialization " + ex.ToString());
            Debug.Assert(false, "Exception occurred during serialization " +
                                ex.ToString());
        }
        return res;
    }


    // Deserialize the given type (only reference types) from an Xml string
    // Eg:
    // MyClass myObj = SerializationHelper.DeserializeFromXml<MyClass>
    //(xmlString);
    public static T TryDeserializeFromXml<T>(this string xml, params Type[] extraTypes)
        where T : class // (only reference types)
    {
        T obj = null;
        try
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof (T), extraTypes);
            obj = (T) xmlSerializer.Deserialize(new StringReader(xml));
        }
        catch (Exception ex)
        {
            Trace.WriteLine("SerializationHelper.DeserializeFromXml<T>: " +
                            "Exception occurred during deserialization " + ex.ToString());
            Debug.Assert(false, "Exception occurred during deserialization " +
                                ex.ToString());
        }
        return obj;
    }


    // Serialize the given type (only reference types) to an Xml filePath
    public static void TrySerializeToXmlFile<T>(this T targetObj, 
        string filePath, params Type[] extraTypes)
        where T : class // (only reference types)
    {
        try
        {
            using (TextWriter tw = new StreamWriter(filePath))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof (T), extraTypes);
                xmlSerializer.Serialize(tw, targetObj);
                tw.Close();
            }
        }
        catch (Exception ex)
        {
            Trace.WriteLine("SerializationHelper.SerializeToXml<T>: " +
                            "Exception occurred during deserialization " + ex.ToString());
            Debug.Assert(false, "Exception occurred during serialization " +
                                ex.ToString());
        }
    }


    // Deserialize the given type (only reference types) from an Xml filePath
    public static T TryDeserializeFromXmlFile<T>(FileInfo file, params Type[] extraTypes)
        where T : class // (only reference types)
    {
        T obj = null;
        try
        {
            using (Stream fs = new FileStream(file.FullName, FileMode.Open))
            {
              // Use an XmlReader as according to the MSDN documentation it
              // "automatically detects and uses the encoding specified by 
              // the XML document."
              using (XmlReader xmlReader = new XmlTextReader(fs))
              {
                 XmlSerializer serializer = new XmlSerializer(typeof (T), extraTypes);
                 obj = (T) serializer.Deserialize(xmlReader);
              }
            }  
            //using (TextReader tr = new StreamReader(file.FullName))
            //{
            //    XmlSerializer serializer = new XmlSerializer(typeof (T), extraTypes);
            //    obj = (T) serializer.Deserialize(tr);
            //    tr.Close();
            //}
        }
        catch (Exception ex)
        {
            Trace.WriteLine("SerializationHelper.TryDeserializeFromXmlFile<T>: " +
                            "Exception occurred during deserialization " + ex.ToString());
            Debug.Assert(false, "Exception occurred during deserialization " +
                                ex.ToString());
        }
        return obj;
    }


}

Using this XmlSerialiser/Deserialiser sample
class XmlSerialiserDeserialiserTester
{
  public void TestTaskSerialisation()
  {
    string testPath = Path.Combine(Path.GetTempPath(), "TestSerializer.xml");

    TaskManager tm = new TaskManager();
    tm.Add(new Task { When = Task.WhenEnum.Fortnight, Displayable = true, 
        Description = "Buy water proofing spray" });
    string serialised = tm.TrySerializeToXml<taskmanager>(); // Serialize
    Debug.WriteLine(serialised);

    TaskManager dtm = serialised.TryDeserializeFromXml<taskmanager>(); // Deserialize
    Debug.Assert(tm.Count == dtm.Count);
    Debug.Assert(tm[0].Description.Equals(dtm[0].Description, 
                                          StringComparison.InvariantCultureIgnoreCase));
  }
}

public class TaskManager : List<Task>
{
}

public class Task
{
 public enum WhenEnum
 {
  Fortnight = 1,
  Month = 2,
  Year = 3,
 }
 public WhenEnum When { get; set; }
 public bool Displayable { get; set; }
 public string Description { get; set; }
}

No comments: