c# xml 序列化、反序列化

ly188:二话不说上代码

 

 public static class XmlSerializeHelper
    {

        //// 示例
        //[XmlRoot("products")]//// 名称
        //public class products
        //{
        //    [XmlElement("product")]//// 标签名称
        //    public List<product> list { get; set; }
        //}
        //public class product
        //{
        //    [XmlElement("orderId")]//// 标签名称
        //    public string orderId { get; set; }
        //    XmlElement("status")]//// 标签名称
        //    public string status { get; set; }
        //    XmlElement("msg")]//// 标签名称
        //    public string msg { get; set; }
        //    XmlElement("info")]//// 标签名称  XmlCDataSection 类型序列化生成CDdata包裹的值反序列化 .Value取值
        //    XmlDataDocument doc = new XmlDataDocument();
        //    XmlCDataSection cd = doc.CreateCDataSection("ly临沂");
        //    public XmlCDataSection info{get;set;}=cd;
        //}


        /// <summary>
        /// 实体转XML字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjToXMLStr<T>(this T obj, Encoding encoding = null) where T : class, new()
        {
            try
            {
                if (encoding == null)
                {
                    encoding = Encoding.UTF8;
                }
                if (obj == null)
                    throw new ArgumentNullException("obj");

                var ser = new XmlSerializer(obj.GetType());
                using (var ms = new MemoryStream())
                {
                    using (var writer = new XmlTextWriter(ms, encoding))
                    {
                        writer.Formatting = Formatting.Indented;
                        ser.Serialize(writer, obj);
                    }
                    var xml = encoding.GetString(ms.ToArray());
                    xml = xml.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
                    xml = xml.Replace("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "");
                    xml = Regex.Replace(xml, @"\s{2}", "");
                    xml = Regex.Replace(xml, @"\s{1}/>", "/>");
                    return xml;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>  
        /// 反序列化xml字符为对象,默认为Utf-8编码  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="xml"></param>  
        /// <returns></returns>  
        public static T XMLToObj<T>(this string xml, Encoding encoding = null)
            where T : class, new()
        {          
            try
            {
                if (encoding == null)
                {
                    encoding = Encoding.UTF8;
                }
                var mySerializer = new XmlSerializer(typeof(T));
                using (var ms = new MemoryStream(encoding.GetBytes(xml)))
                {
                    using (var sr = new StreamReader(ms, encoding))
                    {
                        return (T)mySerializer.Deserialize(sr);
                    }
                }
            }
            catch (Exception e)
            {
                return default(T);
            }
        }

        //对象转XML
        public static string ObjToXml(object obj)
        {
            using (MemoryStream Stream = new MemoryStream())
            {
                XmlSerializer xml = new XmlSerializer(obj.GetType());
                xml.Serialize(Stream, obj);
                Stream.Position = 0;
                StreamReader sr = new StreamReader(Stream);
                string str = sr.ReadToEnd();
                return str;
            }

        }




    }

 

posted @ 2021-10-29 09:07  ly188  阅读(411)  评论(0)    收藏  举报