Serialize Object To XML File - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Serialize Object To XML File

Demo Code


using System.IO;/*from  w  w w.jav a 2s  .c  o  m*/
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System;

public class Main{
        public static void SerializeObjectToFile(object oObject, string sFileName)
        {
            try
            {
                System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(oObject.GetType());

                XmlTextWriter xmlWriter = new XmlTextWriter(sFileName, Encoding.Unicode);
                xmlSerializer.Serialize(xmlWriter, oObject);
                xmlWriter.Close();
            }
            catch (Exception exp)
            {
                throw new XMLSerializerException(string.Format("Error saving object to file: {0}", exp.Message), exp);
            }
        }
}

Related Tutorials