Tuesday, 22 May 2012

Object to XML Conversion in C#


Sample XML is given below
<?xml version="1.0"?>
<note>
    <to>Sumesh</to>
    <from>Ramesh</from>
    <heading>greetings</heading>
    <body>How are you doing</body>
</note>

XML is widely using in data exchange , here is code for generic function for converting object to xml


       public static string ToXML(this object o, Type t)
        {
            string XmlizedString = null;
            MemoryStream memoryStream = new MemoryStream();
            XmlSerializer xs = new XmlSerializer(t);
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);          
            xs.Serialize(xmlTextWriter, o);
            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
            return XmlizedString;


        }

 private static String UTF8ByteArrayToString(Byte[] characters)
        {


            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }