advanced web statistics

XML Serialization with C#

8/2/2007 6:55:58 PM

Probably old-hat but useful nonetheless.  Serializing an object into Xml or binary can be useful at times.  I found some code online awhile back to use and cleaned up a bit.  The Serialize / Deserialize methods are now Generic and I added using constructs.

Serialization
In this case I am taking an object and creating an Xml string.  You could just as easily create an xml file on the server (user settings / preferences, security information, etc...).

private static string UTF8ByteArrayToString(byte[] characters)
{
   return new UTF8Encoding().GetString(characters);
}

public static string SerializeObject<T>(T item)
{
   try
   {
      MemoryStream stream = new MemoryStream();
      using (XmlTextWriter xml = new XmlTextWriter(stream, Encoding.UTF8))
      {
         XmlSerializer xs = new XmlSerializer(typeof(T));
         xs.Serialize(xml, item);
         stream = (MemoryStream) xml.BaseStream;
      }

      return UTF8ByteArrayToString(stream.ToArray());
   }
   catch
   

      return string.Empty; 
   }

}

Deserialization
Just perform the reverse of Serialization!

private static byte[] StringToUTF8ByteArray(string xml)
{
   return new UTF8Encoding().GetBytes(xml);
}

public static T DeserializeObject<T>(string xml)
{
   using (MemoryStream stream = new MemoryStream(StringToUTF8ByteArray(xml)))
   using (new XmlTextWriter(stream, Encoding.UTF8))
   {
      return (T) new XmlSerializer(typeof (T)).Deserialize(stream);
   }
}

Use (Serialization)

Foo foo = new Foo();
foo.Property = ...
foo.AnotherProperty = ...

string
xmlString = SerializeObject(foo);

Use (Deserialization)

Foo foo = DeserializeObject<Foo>(xmlString);

Notes

  • Xml Serialization ONLY serializes public fields and property values
  • Xml Serialization DOES NOT include type information
  • Xml Serialization requires a default constructor (note for ReSharper* jedi's!)
  • Read-only properties ARE NOT serialized

*When creating a class in Visual Studio with ReSharper installed you will get a greyed-out constructor with a red lightbulb.  When you key ALT + ENTER you get the 'Redundant Constructor' message.  I always have a default constructor since I am a fan of overloading constructors so I don't know if this is really an issue.

Easy.

Update
It seems that I am not the only one that edited this original codebase. Paul Whitaker did something very similar a couple of days ago as well!

C#, Code, XML

kick it on DotNetKicks.com

Leave a Comment

   

  Enter the text to proceed!