码迷,mamicode.com
首页 > Web开发 > 详细

.NET XML序列化与反序列化

时间:2014-11-09 20:47:15      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   ar   sp   div   log   bs   

闲着没事,写了两个通用的XML序列化与反序列化的方法。

贴出来当作笔记吧!

 /// <summary>
        /// XML序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="className"></param>
        /// <returns></returns>
        public static string Serializa<T>(T className)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            MemoryStream stream = new MemoryStream();
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = new UTF8Encoding(false);
            settings.Indent = true;
            using (XmlWriter writer = XmlWriter.Create(stream, settings))
            {
                xs.Serialize(writer, className);
            }
            return Encoding.UTF8.GetString(stream.ToArray());
        }



 /// <summary>
        /// XML反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string xmlString)
        {
            StringReader stringReader = new StringReader(xmlString);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            T res = (T)xmlSerializer.Deserialize(stringReader);
            return res;
        }

 

.NET XML序列化与反序列化

标签:des   style   blog   color   ar   sp   div   log   bs   

原文地址:http://www.cnblogs.com/msql/p/4085795.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!