Converts object to XML string - CSharp System.Xml

CSharp examples for System.Xml:XML String

Description

Converts object to XML string

Demo Code

//    This program is free software: you can redistribute it and/or modify
using System.Xml.Serialization;
using System.Xml;
using System.Text;
using System.IO;//from ww  w. j a  v a 2s  .c o m
using System;

public class Main{
        public static void Serialize(object aObject, string aFileName)
        {
            FileStream lStream = new FileStream(aFileName, FileMode.Create);
            XmlSerializer lSerializer = new XmlSerializer(aObject.GetType());
            XmlTextWriter lWriter = new XmlTextWriter(lStream, Encoding.UTF8);
            lSerializer.Serialize(lWriter, aObject);
        }
        #region XML Serialization:
        /// <summary>
        /// Converts object to XML string
        /// </summary>
        /// <param name="aObject">Object to be serialized<</param>/
        /// <returns>string (XML format)</returns>
        public static string Serialize(object aObject)
        {
            string lRes = null;

            MemoryStream lMemStream = new MemoryStream();
            XmlSerializer lSerializer = new XmlSerializer(aObject.GetType());
            XmlTextWriter lWriter = new XmlTextWriter(lMemStream, Encoding.UTF8);
            lSerializer.Serialize(lWriter, aObject);
            lMemStream = (MemoryStream)lWriter.BaseStream;
            UTF8Encoding lEncoding = new UTF8Encoding();
            lRes = lEncoding.GetString(lMemStream.ToArray());

            return lRes;
        }
}

Related Tutorials