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 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("", "");
                return xmlString;
            }
        }

        public static Stream Serializer(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(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(Stream stream) where T : class
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            return (T)xs.Deserialize(stream);
        }

        public static T Deserialize(T1 obj)
            where T : class
            where T1 : class
        {
            return Deserialize(Serializer(obj, true));
        }
        #endregion
    }

 

你可能感兴趣的:(XML序例化工具类)