This method serializes and object into an xml string. - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

This method serializes and object into an xml string.

Demo Code


using System.Xml.Serialization;
using System.Xml;
using System.Text;
using System.IO;/*from   w ww .java2s.c  o  m*/

public class Main{
        /// <summary>
        /// This method serializes and object into an xml string.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="object"></param>
        /// <returns></returns>
        public static string Serialise<T>(T @object)
        {
            var serialiser = new XmlSerializer(@object.GetType());
            var stream = new MemoryStream();
            var writer = new XmlTextWriter(stream, Encoding.UTF8);

            try
            {
                serialiser.Serialize(writer, @object);
                return Encoding.UTF8.GetString(stream.ToArray());
            }
            finally
            {
                writer.Close();
                stream.Close();
            }
        }
}

Related Tutorials