首页 > 代码库 > .NET XML序列化与反序列化

.NET XML序列化与反序列化

闲着没事,写了两个通用的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序列化与反序列化