De Serialize Object to XML - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

De Serialize Object to XML

Demo Code


using System.Xml.Serialization;
using System.Xml;
using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.IO;/*from  w  ww  .j  a  va 2  s.com*/
using System.Collections.Generic;
using System;

public class Main{
        public static T DeSerializeObject<T>(string xmlData = "", string filePath = "")
        {
            T deSerializeObject = default(T);

            if (!String.IsNullOrEmpty(filePath))
                xmlData = File.ReadAllText(filePath);

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            StringReader stringReader = new StringReader(xmlData);

            XmlReader XR = new XmlTextReader(stringReader);

            if (xmlSerializer.CanDeserialize(XR))
            {
                deSerializeObject = (T)xmlSerializer.Deserialize(XR);
            }

            return deSerializeObject;
        }
}

Related Tutorials