Bill Robertson's Blog

February 2010 - Posts

DataContractSerializer Converting Objects to Xml String

This isn't so much a post as a place I could put a common pattern of code.  .NET 3.5 introduced the 10th or 12th iteration of a serializer.  I've stopped to look up this pattern many times and wanted to put a quick sample up with the serialize and deserialize pattern for xml to object mapping.

This will turn the tempData object into an xml string.

 

   1: var serializer = new DataContractSerializer(tempData.GetType());
   2: using (var backing = new System.IO.StringWriter())
   3: using (var writer = new System.Xml.XmlTextWriter(backing))
   4: {
   5:     serializer.WriteObject(writer, tempData);
   6:     data.XmlData = backing.ToString();
   7: }

 

This will return a full object.  This instance is using a generic based approach.

   1: var serializer = new DataContractSerializer(typeof(T));
   2: using (var backing = new System.IO.StringReader(data.XmlData))
   3: using (var reader = new System.Xml.XmlTextReader(backing))
   4: {
   5:     return serializer.ReadObject(reader) as T;
   6: }

 

If there are actual questions about this and how to use it post it below and I might put together a real post about this.
More Posts