Serialize the object to xml text - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Serialize the object to xml text

Demo Code

//  Licensed under the GPLv2: http://dotnetage.codeplex.com/license
using System.Xml.Serialization;
using System.Xml;
using System.IO;//from  w  w  w.  j av a 2s .  c  o m
using System;

public class Main{
        public static string SerializeToXml<T>(T instance)
        {
            return SerializeToXml(instance.GetType(), instance);
        }
        /// <summary>
        /// Serialize the object to xml text
        /// </summary>
        /// <param name="type"></param>
        /// <param name="instance"></param>
        /// <returns></returns>
      public static string SerializeToXml(Type type, object instance)
      {
         XmlSerializer ser = new XmlSerializer(type);
            MemoryStream stream = new MemoryStream();
         XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8);
           
         writer.Formatting = Formatting.None;
         ser.Serialize(writer, instance);
         writer.Flush();
         stream.Position = 0;
         StreamReader reader = new StreamReader(stream,System.Text.Encoding.UTF8);
         string xml = reader.ReadToEnd();
         reader.Close();
         stream.Close();
         writer.Close();
         return xml;
      }
}

Related Tutorials