Wednesday, September 4, 2013

Serialize the class object into XML

Sometimes there is requirement to convert/serialize an object into the XML format so that we can do some operation and manipulation based on the XML data. Here is the simple trick to convert the object data into XML format.

This piece of code will give you the result of Serialized XML by converting an object.

void SerializeXml<T>(string filePath, object objectToSerialize)
        {
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                xmlSerializer.Serialize(fs, objectToSerialize);
                fs.Flush();
                fs.Close();
                fs.Dispose();
            }
            catch (Exception ex)
            {              
            }
        }

Serialize the Class object into XElement

If you have the requirement to convert object of data into the XElement form, then here is the solution for the same. the below piece of code will give output in the form of XElement by serializing the object of the class.
This method takes input as object and cast this with the class as of type "T" and returns the output into XElement format.

XElement ToXElement<T>(object objectToSerialize)
        {
            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    using (TextWriter streamWriter = new StreamWriter(memoryStream))
                    {
                        var xmlSerializer = new XmlSerializer(typeof(T));
                        var xmlSerializerNamespace = new XmlSerializerNamespaces();
                       // To make namespace empty
                        xmlSerializerNamespace.Add(string.Empty, string.Empty);
                        xmlSerializer.Serialize(streamWriter, objectToSerialize, xmlSerializerNamespace);
                        xElement = XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));  
                    }
                }
            }
            catch (Exception ex)
            {
                xElement = null;            
            }
            return xElement;
        }

Motivational qoutes

पूरे विश्वास के साथ अपने सपनों की तरफ बढ़ें। वही ज़िन्दगी जियें जिसकी कल्पना आपने की है।