Share via


XmlSerialization snippet

I keep writing this code - now I can find it on my blog in the future :-)

public static class StringXmlSerializer

{

public static string Serialize<T>(T obj)

{

XmlSerializer s = new XmlSerializer(typeof(T));

StringBuilder sb = new StringBuilder();

StringWriter sw = new StringWriter(sb);

s.Serialize(sw, obj);

return sb.ToString();

}

public static T Deserialize<T>(string str)

{

XmlSerializer s = new XmlSerializer(typeof(T));

StringReader sr = new StringReader(str);

return (T)s.Deserialize(sr);

}

}

Comments

  • Anonymous
    March 24, 2007
    Since you are alread calling your post a 'snippet', why not make it a real Visual Studio code snippet? It's fairly easy to do, as I've described on my own blog: http://blogs.msdn.com/ploeh/archive/2006/03/20/astypeCodeSnippet.aspx. A few other things about your code snippet: StringWrite and StringReader both implement IDisposable, so you should wrap them in using statements. Besides, I'd suggest calling the class 'StringXmlSerializer' instead :)

  • Anonymous
    March 26, 2007
    using blocks - agree. However the local variables sw (and sr) are not really holding on to any unmanaged stuff in this case so I rely on the GC to remove my string and stringbuilder in this case. Dispose of the reader: protected override void Dispose(bool disposing)
    {
       this._s = null;
       this._pos = 0;
       this._length = 0;
       base.Dispose(disposing);
    } Dispose of writer:
    protected override void Dispose(bool disposing)
    {
       this._isOpen = false;
       base.Dispose(disposing);
    } I know it's best practice...
    If you intent to call the method often to (de-)serialize the same types caching the XmlSerializer objects will improve performance. -again-snippet not meant as a guiding example on how to write code - merely somthing I use occasionally when playing with xsd.exe and Xml Serialization.
     

  • Anonymous
    March 26, 2007
    telerik radEditor for Office SharePoint Server 2007 has been officially released! + Telerik for MCMS...