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

namespace Siger.Middlelayer.Common.Helpers
{
    public class XmlHelper
    {
        /// <summary>
        /// xml entity 转字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serialize<T>(T obj)
        {
            var serializer = new XmlSerializer(typeof(T));
            var writer = new StringWriter(CultureInfo.InvariantCulture);
            serializer.Serialize(writer, obj);
            var xml = writer.ToString();
            writer.Close();
            writer.Dispose();

            return xml;
        }

        /// <summary>
        /// xml字符串转entity
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string xml)
        {
            var serializer = new XmlSerializer(typeof(T));
            var reader = new StringReader(xml);
            var result = (T)(serializer.Deserialize(reader));
            reader.Close();
            reader.Dispose();

            return result;
        }
    }
}
