Xml serialize and deserialize an object

June 20th, 2008 by ganton | Print

Some time ago, I needed to serialize and deserialize different types of objects to/from XML. Because of that I decided to create a class with template methods to do this. The name of the class is XmlConverter (see below).

   1: public static class XmlConverter

   2: {

   3:  

   4: public static string ToXml(T value) where T : new()

   5: {

   6: return ToXml(value, Encoding.UTF8);

   7: }

   8:  

   9: public static string ToXml(T value, Encoding encoding) where T : new()

  10: {

  11: try

  12: {

  13: using (MemoryStream stream = new MemoryStream())

  14: {

  15: using (TextWriter writer = new StreamWriter(stream, encoding))

  16: {

  17: XmlSerializer serializer = new XmlSerializer(typeof(T));

  18: serializer.Serialize(writer, value);

  19: int cnt = (int)stream.Length;

  20: byte[] arr = new byte[cnt];

  21: stream.Seek(0, SeekOrigin.Begin);

  22: stream.Read(arr, 0, cnt);

  23: return encoding.GetString(arr, 0, arr.Length).Trim();

  24: }

  25: }

  26: }

  27: catch

  28: {

  29: }

  30: return null;

  31: }

  32:  

  33: public static T FromXml(string xml) where T : new()

  34: {

  35: try

  36: {

  37: using (StringReader stream = new StringReader(xml))

  38: {

  39: using (XmlTextReader reader = new XmlTextReader(stream))

  40: {

  41: XmlSerializer serializer = new XmlSerializer(typeof(T));

  42: return (T)serializer.Deserialize(reader);

  43: }

  44: }

  45: }

  46: catch

  47: {

  48: }

  49: return default(T);

  50: }

  51: }

You can use to serialize objects but each object must have default constructor, otherwise the object can not be serialized/deserialized.

[Update 06/24/2008: Each generic method has updated to has a constraint on its type parameter "new()". It will ensure that all provided types for serialization will have parameterless constructor.]

If you’d like to serialize or deserialize a Dictionary<TKey, TValue> you may need to develop your own dictionary which should implement IXmlSerializable (see Paul Welter’s XML Serializable Generic Dictionary).

Example: Let’s assume that we have a class name Contact

   1: public struct Contact

   2: {

   3: public string Name { get; set; }

   4: public int Age { get; set; }

   5: public string Address { get; set; }

   6: public string Phone { get; set; }

   7: }

Next snippet will create a contact and will serialize/deserialize it. After serialization contactXml will contain xml representation of the contact and after deserialization restoredContact will contain a copy of the original contact values.

 

   1: Contact contact = new Contact()

   2: {

   3:     Name = "Anton",

   4:     Age = 28,

   5:     Address = "Sofia",

   6:     Phone = "(000) 123 456 789"

   7: };

   8:  

   9: string contactXml = XmlConverter.ToXml<Contact>(contact);

  10:  

  11: Contact restoredContact = XmlConverter.FromXml<Contact>(contactXml);

The output xml for serialized Contact object is

   1:  

   2: http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

   3: Anton

   4: 28

   5:  

   6: Sofia

   7: (000) 123 456 789

   8:  

   9:  

Next snippet will create a list of contacts and serialize/deserialize them. After serialization listXml will contain xml representation of list of contacts and after deserialization restoredList will contain a copy of the original contacts values from the list.

   1: List<Contact> list = new List()

   2: {

   3:     new Contact()

   4:     {

   5:         Name = "Anton",

   6:         Age = 28,

   7:         Address = "Sofia",

   8:         Phone = "(000) 123 456 789"

   9:     },

  10:     new Contact()

  11:     {

  12:         Name = "Anton",

  13:         Age = 28,

  14:         Address = "Sofia",

  15:         Phone = "(000) 123 456 789"

  16:     }

  17: };

  18:  

  19: var listXml = XmlConverter.ToXmlList<<Contact>>(list);

  20:  

  21: List<Contact> restoredList = XmlConverter.FromXml<List<Contact>>(listXml); 

  22:  

Note that this method of XML serialization will be slow if you have a thousands of objects in a list. Last time I had such amount of objects I used to implement XmlSerializable per each object and to serialize them manually. It was much faster than standard XML serialization using by implementation of this class.

4 Responses to “Xml serialize and deserialize an object”

  1. Serialize/Deserialize a Font and Color to/from XML : Anton Gochev’s Weblog Says:

    [...] is an example of serializing and deserializing an instance of UIAppearance class. This example uses XmlConverter to serialize the [...]

  2. XmlConverter - serialize/deserialize an object to/from Xml in VB.Net : Anton Gochev’s Weblog Says:

    [...] is an implementation using VB.Net of XmlConverter class from my old post. I’ll not rewrite the post but just put the code and sample of its use. The idea is to allow [...]

  3. XmlConverter - serialize/deserialize an object to/from Xml (continue) : Anton Gochev’s Weblog Says:

    [...] days ago I wrote about a static class named XmlConverter. It contains few generic methods which allow an object to be serialized to XML or deserialized [...]

  4. Anton Gochev’s Weblog » XmlConverter performance improvement Says:

    [...] XmlConverter - serialize/deserialize an object to/from Xml Popular Posts [...]

Leave a Reply