Skip to content

Quick and dirty way to serialize an object to XML and back

A lot of time I just want to quickly look at how an object graph will be serialized to XML. I end up writing quick and dirty code like below time after time since I cannot find the code snippet I had written a while back. I am documenting it here so I do not have to write it again when I need it next time.

public class SerUtils
{
  public static string SerializeToString(T source)
  {
    if(null == source)
	    return string.Empty;
    	
    XmlSerializer ser = new XmlSerializer(source.GetType());
    MemoryStream ms = new MemoryStream();
    ser.Serialize(ms, source);			
    ms.Flush();
    ms.Position = 0;
    StreamReader sr = new StreamReader(ms);
    string s = sr.ReadToEnd();
    return s;
  }

  public static T DeserializeFromString(string xml)
  {
    if(string.Empty == xml)
	    return default(T);

    XmlSerializer ser = new XmlSerializer(typeof(T));
    MemoryStream ms = new MemoryStream();
    StreamWriter sw = new StreamWriter(ms);
    sw.Write(xml);
    sw.Flush();
    ms.Position = 0;
    return (T) ser.Deserialize(ms);
  }
}

Don’t use this in production!