Deserialize the object from XML file - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Deserialize the object from XML file

Demo Code

//  Licensed under the GPLv2: http://dotnetage.codeplex.com/license
using System.Xml.Serialization;
using System.Xml;
using System.IO;//from   www. j a va  2s. co m
using System;

public class Main{
        public static T DeserializeFormXmlFile<T>(string fileName)
        {
            return (T)DeserializeFormXmlFile(fileName, typeof(T));
        }
        /// <summary>
        /// Deserialize the object from file
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="type"></param>
        /// <returns></returns>
      public static object DeserializeFormXmlFile(string fileName,Type type)
      {
            try
            {
                XmlSerializer ser = new XmlSerializer(type);
                FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                object obj = ser.Deserialize(stream);
                stream.Close();
                return obj;
            }
            catch(Exception e) 
            {
                throw new XmlDeserializeException(fileName, type.ToString()+" "+e.Message);
                //return null;
            }
      }
}

Related Tutorials