using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace CommonClassLib
{
    public class XmlSerialization
    {
        /// <summary> 反序列化
        /// 反序列化 
        /// </summary> 
        /// <param name="type">类型</param> 
        /// <param name="xml">XML字符串</param> 
        /// <returns></returns> 
        public static T DeSerialize<T>(string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(typeof(T));

                    return (T)xmldes.Deserialize(sr);
                }
            }
            catch //(Exception e)
            {
                return default(T);
            }
        }

        /// <summary> 序列化XML文件
        /// 序列化XML文件 
        /// </summary> 
        /// <param name="type">类型</param> 
        /// <param name="obj">对象</param> 
        /// <returns></returns> 
        public static string Serializer<T>(T t)
        {
            MemoryStream Stream = new MemoryStream();

            //创建序列化对象 
            XmlSerializer xml = new XmlSerializer(typeof(T));

            try
            {
                //序列化对象 
                xml.Serialize(Stream, t);
            }
            catch (InvalidOperationException)
            {
                throw;
            }

            Stream.Position = 0;

            StreamReader sr = new StreamReader(Stream);

            string str = sr.ReadToEnd().Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", string.Empty);

            return str;
        }
    }
}
