代码改变世界

.NET XML序列化与反序列化

2014-11-09 20:05  sql_manage  阅读(714)  评论(0编辑  收藏  举报

闲着没事,写了两个通用的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;
        }