How to use XMLSerializer Class


Hi Friends, Here i am going to discuss with you about XMLSerializer Class under namespace System.Xml.Serialization.XmlSerializer. The XmlSerializer enables you to control how objects are encoded into XML. Here is the small code snippet which you can use to create XML file or XML String from any Serialize Object using XMLSerializer Class.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace MBXml
{
    /// <summary>  
    /// MBXmlSerializer Class  
    /// </summary>  
    public class MBXmlSerializer
    {
        /// <summary>  
        /// Create XML from Serialize Object  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="xmlObject"></param>  
        /// <returns></returns>  
        public string GetXml<T>(T xmlObject)
        {

            var serializer = new XmlSerializer(typeof(T));
            string utf8;
            using (StringWriter writer = new Utf8StringWriter())
            {
                serializer.Serialize(writer, xmlObject);
                utf8 = writer.ToString();
            }
            return utf8.ToString();
        }
        /// <summary>  
        /// Utf8StringWriter Class  
        /// </summary>  
        private class Utf8StringWriter : StringWriter
        {
            public override Encoding Encoding
            {
                get { return Encoding.UTF8; }
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s