Bill Robertson's Blog

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.

Comments

Ritesh Ramesh said:

I found that the generated xml string using your method appends "Field" to all the elements .

Any idea how I can get rid of this?

# July 27, 2010 8:38 PM

Bill Robertson said:

Ritesh, have you looked at [IgnoreDataMember]?

# August 4, 2010 3:56 PM

Ramon M. said:

Thanks for the sample code. It's been very useful for me!!

# September 20, 2010 11:02 AM

Matthew E. said:

Saved me again billrob. <3

# December 1, 2010 5:08 PM

chirurgia estetica said:

Thanks for sharing, this code is very useful.

# February 23, 2011 2:07 AM