Serializes an Entity to XML using the XmlSerializer. - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Serializes an Entity to XML using the XmlSerializer.

Demo Code


using System.Xml.Serialization;
using System.Xml;
using System.Text;
using System.Security;
using System.Runtime.Serialization;
using System.IO;//www . j a  v a  2  s .co  m
using System;

public class Main{
        /// <summary>
        /// Serializes an Entity to XML using the <see cref="System.Xml.Serialization.XmlSerializer"/>.
        /// </summary>
        /// <typeparam name="T">Type of the Entity.</typeparam>
        /// <param name="entity">the Entity to serialize.</param>
        /// <param name="extraTypes">A Type array of additional object types to serialize. <see cref="System.Type"/></param>
        /// <returns>the XML of the Entity as <see cref="System.String"/>.</returns>
        public static String EntityToXml<T>(T entity, params Type[] extraTypes)
        {
            MemoryStream stream = null;
            TextWriter writer = null;
            try
            {
                stream = new MemoryStream(); // read XML in memory
                writer = new StreamWriter(stream, Encoding.UTF8);
                // get serialize object
                XmlSerializer serializer = new XmlSerializer(typeof(T), extraTypes);
                serializer.Serialize(writer, entity); // read object
                var count = (Int32)stream.Length; // saves object in memory stream
                Byte[] arr = new Byte[count];
                stream.Seek(0, SeekOrigin.Begin);
                // copy stream contents in byte array
                stream.Read(arr, 0, count);
                UTF8Encoding utf = new UTF8Encoding(); // convert byte array to string
                //return utf.GetString(arr).Trim().Replace("\n", "").Replace("\r", "");
                return utf.GetString(arr);
            }
            catch
            {
                return String.Empty;
            }
            finally
            {
                if ( writer != null )
                    writer.Close();  // Also closes the underlying stream!
                //if ( stream != null )
                //    stream.Dispose();
            }
        }
}

Related Tutorials