• XML序例化工具类


    Model:

        [XmlRoot(ElementName = "root")]
        public class BookModel
        {
            [XmlElement]
            public string BookID { get; set; }
    
            [XmlElement]
            public string BookName { get; set; }
        }

    XmlUtil 工具类:

        public class XmlUtil
        {
            #region 序列化
            public static string Serializer<T>(T obj) where T : class
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    XmlSerializer xs = new XmlSerializer(typeof(T));
                    xs.Serialize(ms, obj);
                    ms.Position = 0;
                    StreamReader sr = new StreamReader(ms);
                    string xmlString = sr.ReadToEnd();
                    sr.Dispose();
                    ms.Dispose();
                    xmlString = xmlString.Replace("<?xml version="1.0"?>", "<?xml version="1.0" encoding="GBK"?>");
                    return xmlString;
                }
            }
    
            public static Stream Serializer<T>(T obj, bool isStream) where T : class
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    XmlSerializer xs = new XmlSerializer(typeof(T));
                    xs.Serialize(ms, obj);
                    ms.Position = 0;
                    return ms;
                }
            }
            #endregion
    
            #region 反序列化
            public static T Deserialize<T>(string xmlString) where T : class
            {
                StringReader sr = new StringReader(xmlString);
                XmlSerializer xs = new XmlSerializer(typeof(T));
                T obj = (T)xs.Deserialize(sr);
                sr.Dispose();
                return obj;
            }
    
            public static T Deserialize<T>(Stream stream) where T : class
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                return (T)xs.Deserialize(stream);
            }
    
            public static T Deserialize<T, T1>(T1 obj)
                where T : class
                where T1 : class
            {
                return Deserialize<T>(Serializer<T1>(obj, true));
            }
            #endregion
        }
  • 相关阅读:
    在web.config 的config
    有道理
    showModalDialog和showModelessDialog使用心得
    VBScript的 trim()
    RetroGuard的使用方法(转)
    NHibernate 的语句的问题
    Web控件TreeView展开无闪烁的两个解决方法
    如何在类库项目中添加Web窗体文件
    签名活动链接
    __EVENTTARGET为空或不是对象
  • 原文地址:https://www.cnblogs.com/lisweden/p/5144726.html
Copyright © 2020-2023  润新知