Serialize Object To Xml String - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Serialize Object To Xml String

Demo Code


using System.Xml.Serialization;
using System.Xml;
using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.IO;//from w  w w  .  ja  va 2 s . c om
using System.Collections.Generic;
using System;

public class Main{
        public static string SerializeObjectToXmlString<T>(T TModel)
        {
            string xmlData = String.Empty;

            XmlSerializerNamespaces EmptyNameSpace = new XmlSerializerNamespaces();
            EmptyNameSpace.Add("", "");

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            MemoryStream memoryStream = new MemoryStream();
            XmlTextWriter xmlWriter = new XmlTextWriter(memoryStream, new System.Text.UTF8Encoding(false));
            xmlWriter.Formatting = Formatting.Indented;

            xmlSerializer.Serialize(xmlWriter, TModel, EmptyNameSpace);

            memoryStream = (MemoryStream)xmlWriter.BaseStream;
            xmlData = UTF8ByteArrayToString(memoryStream.ToArray());

            return xmlData;
        }
}

Related Tutorials