Sunday, September 15, 2013

Object And XML Serialization

In .Net, we can serialize and deserialize an object to/from an XML string using XmlSerializer.

The following methods provide easy ways to do this, with overloads that accept an existing instance of XmlSerializer if there is any.
  • Note: To avoid any performance hit, it's always better to use back an existing instance of XmlSerializer for the same object type if possible.

using System.IO;
using System.Xml;
using System.Xml.Serialization;

...

/// <summary>
/// Serializes an object to XML string.
/// </summary>
/// <param name="obj">Object to be serialized.</param>
/// <returns>Serialized XML string.</returns>
public static string SerializeObjectToXML(object obj)
{
    return SerializeObjectToXML(obj, null);
}

/// <summary>
/// Serializes an object to XML string.
/// </summary>
/// <param name="obj">Object to be serialized.</param>
/// <param name="serializer">An XmlSerializer instance to be used. If null, a new instance will be used.</param>
/// <returns>Serialized XML string.</returns>
public static string SerializeObjectToXML(object obj, XmlSerializer serializer)
{
    string xmlString;

    using (StringWriter stringWriter = new StringWriter())
    {
        if (serializer == null)
            serializer = new XmlSerializer(obj.GetType());

        serializer.Serialize(stringWriter, obj);
        stringWriter.Flush();
        xmlString = stringWriter.ToString();
    }

    return xmlString;
}

/// <summary>
/// Deserializes XML string to an object.
/// </summary>
/// <param name="xmlString">Serialized XML string.</param>
/// <param name="objType">Type of object to deserialize.</param>
/// <returns>Object deserialized from XML.</returns>
public static object DeserializeXMLToObject(string xmlString, Type objType)
{
    return DeserializeXMLToObject(xmlString, objType, null);
}

/// <summary>
/// Deserializes XML string to an object.
/// </summary>
/// <param name="xmlString">Serialized XML string.</param>
/// <param name="objType">Type of object to deserialize.</param>
/// <param name="serializer">An XmlSerializer instance to be used. If null, a new instance will be used.</param>
/// <returns>Object deserialized from XML.</returns>
public static object DeserializeXMLToObject(string xmlString, Type objType, XmlSerializer serializer)
{
    object obj = null;

    using (StringReader stringReader = new StringReader(xmlString))
    {
        if (serializer == null)
            serializer = new XmlSerializer(objType);

        obj = serializer.Deserialize(stringReader);
        stringReader.Close();
    }

    return obj;
}


If you find this post helpful, would you buy me a coffee?


1 comment:

  1. Man I love this site. It is just so awesome. Whatever you want, all are available here.

    www.imarksweb.org

    ReplyDelete