zoukankan      html  css  js  c++  java
  • 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
        }
  • 相关阅读:
    tableView cell 设置圆角 响应链
    iOS
    git code 初次上传
    隐藏导航栏,偏移20PX
    Mysql数据库远程连接
    umeng推送, 生产环境deviceToken失效可能原因
    KeyChainWrapper
    UIVisualEffectView(高斯模糊效果)
    UVA 11582 Colossal Fibonacci Numbers! 快速幂
    HDU 2859 Phalanx DP
  • 原文地址:https://www.cnblogs.com/lisweden/p/5144726.html
Copyright © 2011-2022 走看看