Thursday, June 6, 2013

Convert Object to XML in C#


Add following name space:

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


Then add below code in class file

/// <summary>
/// Serializes a class to xml text
/// </summary>
/// <param name="item">Class to be converted to XML</param>
/// <returns>XML string representing class</returns>
public static string SerializeObjectToXML(object item)
{
    try
    {
        string xmlText;
        //Get the type of the object
        Type objectType = item.GetType();
        //create serializer object based on the object type
        XmlSerializer xmlSerializer = new XmlSerializer(objectType);
        //Create a memory stream handle the data
        MemoryStream memoryStream = new MemoryStream();
        //Create an XML Text writer to serialize data to
        using (XmlTextWriter xmlTextWriter =
            new XmlTextWriter(memoryStream, Encoding.UTF8)
                { Formatting = Formatting.Indented })
        {
            //convert the object to xml data
            xmlSerializer.Serialize(xmlTextWriter, item);
            //Get reference to memory stream
            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            //Convert memory byte array into xml text
            xmlText = new UTF8Encoding().GetString(memoryStream.ToArray());
            //clean up memory stream
            memoryStream.Dispose();
            return xmlText;
        }
    }
    catch (Exception e)
    {
        //There are a number of reasons why this function may fail
        //usually because some of the data on the class cannot
        //be serialized.
        System.Diagnostics.Debug.Write(e.ToString());
        return string.empty;
    }
}

No comments:

Post a Comment