.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; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。