Wednesday, September 4, 2013

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;
        }

No comments:

Post a Comment

Put your comments here

Motivational qoutes

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