Friday, August 29, 2014

Serialize a C# object to a string of XML.

This offers something like:

string xml = null;
using (var memoryStream = new MemoryStream())
{
   using (var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
   {
      var xmlSerializer = new XmlSerializer(whatever.GetType());
      xmlSerializer.Serialize(xmlTextWriter, whatever);
      using (var xmlTextWriterMemoryStream = (MemoryStream)
            xmlTextWriter.BaseStream)
      {
         UTF8Encoding utf8Encoding = new UTF8Encoding();
         xml = utf8Encoding.GetString(xmlTextWriterMemoryStream
               .ToArray()).Substring(1);
      }
   }
}

 
 

This suggests a way to get the string back to a C# type might look something like this:

Whatever whatever;
using (var stringReader = new StringReader(xml))
{
   var xmlSerializer = new XmlSerializer(typeof(Whatever));
   whatever = (Whatever) xmlSerializer.Deserialize(stringReader);
}

 
 

If you serialize a type to XML in C#, put it in a string, and then, while stopped at a breakpoint in Visual Studio, copy and paste the text out of the string, remember to take out the backslashes before you do anything substantive with it. Otherwise the backslashes will cause C# to blow up when you attempt to deserialize.

No comments:

Post a Comment