首页 > 代码库 > .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序列化与反序列化
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。