Deserialize the object from XML text - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Deserialize the object from XML text

Demo Code

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

public class Main{
        public static T DeserializeFromXmlText<T>(string xml)
        {
            return (T)DeserializeFromXmlText(xml, typeof(T));
        }
        /// <summary>
        /// Deserialize the object from text
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="type"></param>
        /// <returns></returns>
      public static object DeserializeFromXmlText(string xml, Type type)
      {
         MemoryStream stream = new MemoryStream();
         StreamWriter writer = new StreamWriter(stream,System.Text.Encoding.UTF8);
         writer.Write(xml);
         writer.Flush();
         stream.Position = 0;

            XmlSerializer serializer = new XmlSerializer(type);
         object obj=serializer.Deserialize(stream);
         writer.Close();
         stream.Close();
         return obj;
      }
}

Related Tutorials