Deserialize Object From XML File - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Deserialize Object From XML File

Demo Code


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

public class Main{
        public static T DeserializeObjectFromFile<T>(string sFileName)
        {
            object oRetval = null;

            try
            {
                if (File.Exists(sFileName))
                {
                    System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

                    XmlTextReader oXmlReader = new XmlTextReader(sFileName);

                    if (xmlSerializer.CanDeserialize(oXmlReader))
                        oRetval = xmlSerializer.Deserialize(oXmlReader);

                    oXmlReader.Close();

                }
                else
                {
                    throw new IOException(string.Format("File '{0}' not found.", sFileName));
                    //throw (new Exception(string.Format("File '{0}' not found.", sFileName)));
                }
            }
            catch (Exception exp)
            {
                throw new XMLSerializerException(string.Format("Error loading object from file: {0}", exp.Message), exp);
            }

            return (T)oRetval;
        }
        public static object DeserializeObjectFromFile(Type tOjectType, string sFileName)
        {
            object oRetval = null;

            try
            {
                if (File.Exists(sFileName))
                {
                    System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(tOjectType);

                    XmlTextReader oXmlReader = new XmlTextReader(sFileName);

                    if (xmlSerializer.CanDeserialize(oXmlReader))
                        oRetval = xmlSerializer.Deserialize(oXmlReader);

                    oXmlReader.Close();

                }
                else
                {
                    throw new IOException(string.Format("File '{0}' not found.", sFileName));
                    //throw (new Exception(string.Format("File '{0}' not found.", sFileName)));
                }
            }
            catch (Exception exp)
            {
                throw new XMLSerializerException(string.Format("Error loading object from file: {0}", exp.Message), exp);
            }

            return oRetval;
        }
}

Related Tutorials