C#对于XML的序列化与反序列化提供了很好的支持,我们只需要引用System.Xml的命名空间即可,无需使用第三方库,下面简单实现了一个XML的序列化与反序列化的帮助类。
using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; namespace XmlHelper { public static class XmlSerializeHelper { /// <summary> /// XML序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string XmlSerializer<T>(T obj) { var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(false), Indent = true }; using (var ms = new MemoryStream()) { using (var xw = XmlWriter.Create(ms, settings)) { var ns = new XmlSerializerNamespaces(); ns.Add("", ""); var serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(xw, obj, ns); return Encoding.UTF8.GetString(ms.ToArray()); } } } /// <summary> /// XML反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="XmlString"></param> /// <returns></returns> public static T XmlDeserialize<T>(this string XmlString) { if (string.IsNullOrEmpty(XmlString)) throw new ArgumentNullException("s"); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(XmlString))) { using (var xr = XmlReader.Create(ms)) { var xmlSerializer = new XmlSerializer(typeof(T)); return (T)xmlSerializer.Deserialize(xr); } } } } }