Serialize object to XML with format settings - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Serialize object to XML with format settings

Demo Code


using System.Xml.Serialization;
using System.Xml;
using System.Text;
using System.IO;/*w  ww  .j  a  v  a  2s . com*/
using System.Collections.Generic;
using System.Collections;
using System;

public class Main{
        public static string Serialize<T>(object data, bool omitXmlDeclaration = true, bool omitXmlNamespace = true,
            bool indented = false, Encoding encoding = null)
        {
            if( encoding == null )
                encoding = UnicodeEncoding.Unicode;

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = omitXmlDeclaration;
            settings.ConformanceLevel = ConformanceLevel.Auto;
            settings.CloseOutput = false;
            settings.Encoding = encoding;
            settings.Indent = indented;

            MemoryStream ms = new MemoryStream();
            XmlSerializer s = new XmlSerializer( typeof( T ) );
            XmlWriter w = XmlWriter.Create( ms, settings );
            if( omitXmlNamespace )
            {
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add( "", "" );
                s.Serialize( w, data, ns );
            }
            else
            {
                s.Serialize( w, data );
            }
            string result = encoding.GetString( ms.GetBuffer(), 0, (int)ms.Length );
            w.Close();
            return result;
        }
}

Related Tutorials