Deserialize Collection From XML File - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Deserialize Collection From XML File

Demo Code


using System.IO;/*from   w w w  .j  av a  2  s.  c  om*/
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System;

public class Main{
        public static T DeserializeCollectionFromFile<T>(string sFilename, string sRootElementName)
        {
            object oRetval = null;

            try
            {
                if (File.Exists(sFilename))
                {
                    XmlRootAttribute ra = new XmlRootAttribute();
                    ra.Namespace = string.Empty;
                    ra.ElementName = sRootElementName;
                    System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T), ra);

                    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 DeserializeCollectionFromFile(Type tOjectType, string sFilename, string sRootElementName)
        {
            object oRetval = null;

            try
            {
                if (File.Exists(sFilename))
                {
                    XmlRootAttribute ra = new XmlRootAttribute();
                    ra.Namespace = string.Empty;
                    ra.ElementName = sRootElementName;
                    System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(tOjectType, ra);

                    XmlTextReader oXmlReader = new XmlTextReader(sFilename);

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

                    oXmlReader.Close();

                }
                else
                {
                    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