天天看點

C#将實體對象轉換成XML

C# 将實體對象轉換成XML

  • ​​将實體對象轉換成XML​​

将實體對象轉換成XML

using System;
using System.IO;
using System.Xml.Serialization;

namespace YG._CommonFunctions
{
    /// <summary>
    /// 将實體對象轉換成XML
    /// </summary>
    public static class Class2XML
    {
        /// <typeparam name="T">實體類型</typeparam>
        /// <param name="obj">實體對象</param>
        public static string ToXml<T>(T obj)
        {
            try
            {
                MemoryStream stream = new MemoryStream();
                XmlSerializer xmlSer = new XmlSerializer(typeof(T));
                xmlSer.Serialize(stream, obj);

                stream.Position = 0;
                StreamReader sr = new StreamReader(stream);
                return sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw new Exception("将實體對象轉換成XML異常", ex);
            }
        }

        /// <summary>
        /// 将XML轉換成實體對象
        /// </summary>
        /// <typeparam name="T">實體類型</typeparam>
        /// <param name="strXML">XML</param>
        public static T ToClass<T>(string strXML) where T : class
        {
            try
            {
                using StringReader sr = new StringReader(strXML);
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return serializer.Deserialize(sr) as T;
            }
            catch (Exception ex)
            {
                throw new Exception("将XML轉換成實體對象異常", ex);
            }
        }
    }
}