Welcome to MSDN Blogs Sign in | Join | Help

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);

   }

}

Published Saturday, March 24, 2007 4:39 PM by jimmytr
Filed under:

Comments

# re: XmlSerialization snippet

Sunday, March 25, 2007 3:54 AM by ploeh

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 :)

# re: XmlSerialization snippet

Monday, March 26, 2007 7:19 PM by jimmytr

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.

 

# Link Listing - March 26, 2007

Tuesday, March 27, 2007 12:25 AM by Christopher Steen

telerik radEditor for Office SharePoint Server 2007 has been officially released! + Telerik for MCMS...

Anonymous comments are disabled
 
Page view tracker