Create Object Instance From Xml - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Create Object Instance From Xml

Demo Code


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

public class Main{
        public static T CreateInstanceFromXml<T>(string filename) where T : new()
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            XmlReader reader = new XmlTextReader(filename);
            try
            {
                return (T)xmlSerializer.Deserialize(reader);
            }
            finally
            {
                reader.Close();
            }
        }
        public static object Deserialize(string xmlString, Type type, Encoding encoding)
        {
            XmlSerializer s = new XmlSerializer(type);
            byte[] buffer = encoding.GetBytes(xmlString);
            MemoryStream ms = new MemoryStream(buffer);
            XmlReader reader = new XmlTextReader(ms);

            try
            {
                object o = s.Deserialize(reader);
                return o;
            }
            finally
            {
                reader.Close();
            }
        }
        public static object Deserialize(string xmlString, Type type)
        {
            return Deserialize(xmlString, type, Encoding.UTF8);
        }
}

Related Tutorials