XmlConverter - serialize/deserialize an object to/from Xml

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).

public static class XmlConverter
{

    public static string ToXml<T>(T value) where T : new()
    {
        return ToXml<T>(value, Encoding.UTF8);
    }

    public static string ToXml<T>(T value, Encoding encoding) where T : new()
    {
        try
        {
            using (MemoryStream stream = new MemoryStream())
            {
                using (TextWriter writer = new StreamWriter(stream, encoding))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    serializer.Serialize(writer, value);
                    int cnt = (int)stream.Length;
                    byte[] arr = new byte[cnt];
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.Read(arr, 0, cnt);
                    return encoding.GetString(arr, 0, arr.Length).Trim();
                }
            }
        }
        catch
        {
        }
        return null;
    }

    public static T FromXml<T>(string xml) where T : new()
    {
        try
        {
            using (StringReader stream = new StringReader(xml))
            {
                using (XmlTextReader reader = new XmlTextReader(stream))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return (T)serializer.Deserialize(reader);
                }
            }
        }
        catch
        {
        }
        return default(T);
    }
}

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

public struct Contact
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
}

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.

Contact contact = new Contact()
{
    Name = "Anton",
    Age = 28,
    Address = "Sofia",
    Phone = "(000) 123 456 789"
};

string contactXml = XmlConverter.ToXml &amp; lt; contact &amp; gt; (contact);

Contact restoredContact = XmlConverter.FromXml &amp; lt; contact &amp; gt; (contactXml);

The output xml for serialized Contact object is

<?xml version="1.0" encoding="utf-8"?>
<contact xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>" xmlns:xsd="<a href="http://www.w3.org/2001/XMLSchema">http://www.w3.org/2001/XMLSchema</a>">
    <name>Anton</name>
    <age>28</age>
    <address>Sofia</address>
    <phone>(000) 123 456 789</phone>
</contact>

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.

List<contact> list = new List<contact>()
{
    new Contact()
    {
        Name = "Anton",
        Age = 28,
        Address = "Sofia",
        Phone = "(000) 123 456 789"
    },
    new Contact()
    {
        Name = "Anton",
        Age = 28,
        Address = "Sofia",
        Phone = "(000) 123 456 789"
    }
};

var listXml = XmlConverter.ToXml<list<contact>>(list);

List<contact> restoredList = XmlConverter.FromXml<list<contact>>(listXml);

The output xml for serialized list of contacts is

<?xml version="1.0" encoding="utf-8"?>
<arrayOfContact xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>" xmlns:xsd="<a href="http://www.w3.org/2001/XMLSchema">http://www.w3.org/2001/XMLSchema</a>">
    <contact>
        <name>Anton</name>
        <age>28</age>
        <address>Sofia</address>
        <phone>(000) 123 456 789</phone>
    </contact>
    <contact>
        <name>Anton</name>
        <age>28</age>
        <address>Sofia</address>
        <phone>(000) 123 456 789</phone>
    </contact>
</arrayOfContact>

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 “XmlConverter - serialize/deserialize an object to/from Xml”

  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