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.

  1.  
  2. public class SerUtils
  3. {
  4. public static string SerializeToString<T>(T source)
  5. {
  6. if(null == source)
  7. return string.Empty;
  8.  
  9. XmlSerializer ser = new XmlSerializer(source.GetType());
  10. MemoryStream ms = new MemoryStream();
  11. ser.Serialize(ms, source);
  12. ms.Flush();
  13. ms.Position = 0;
  14. StreamReader sr = new StreamReader(ms);
  15. string s = sr.ReadToEnd();
  16. return s;
  17. }
  18.  
  19. public static T DeserializeFromString<T>(string xml)
  20. {
  21. if(string.Empty == xml)
  22. return default(T);
  23.  
  24. XmlSerializer ser = new XmlSerializer(typeof(T));
  25. MemoryStream ms = new MemoryStream();
  26. StreamWriter sw = new StreamWriter(ms);
  27. sw.Write(xml);
  28. sw.Flush();
  29. ms.Position = 0;
  30. return (T) ser.Deserialize(ms);
  31. }
  32. }
  33.  

Don't use this in production!