这篇文章给大家介绍如何在C#项目中实现对象序列化XML,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
首先,需要用到的是这两个命名空间(主要)
using System.Xml; using System.Xml.Serialization;
然后序列化和反序列化的方式和Json一样。(后面提供封装方法)
string result = XmlSerializeHelper.Serialize<test>(new test { name = "Seven", cardId = "663927", age = 15, currentTime = DateTime.Now }); Console.WriteLine(result); test test2 = XmlSerializeHelper.DeSerialize<test>(result);
下面来看封装类
public class XmlSerializeHelper { //对象转XML public static string ObjToXml(object obj) { using (MemoryStream Stream = new MemoryStream()) { XmlSerializer xml = new XmlSerializer(obj.GetType()); xml.Serialize(Stream, obj); Stream.Position = 0; StreamReader sr = new StreamReader(Stream); return sr.ReadToEnd(); } } public static string Serialize<T>(T obj) { return Serialize<T>(obj, Encoding.UTF8); } /// <summary> /// 实体对象序列化成xml字符串 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string Serialize<T>(T obj, Encoding encoding) { try { if (obj == null) { throw new ArgumentNullException("obj"); } var ser = new XmlSerializer(obj.GetType()); using (var ms = new MemoryStream()) { using (var writer = new XmlTextWriter(ms, encoding)) { writer.Formatting = Formatting.Indented; ser.Serialize(writer, obj); } var xml = encoding.GetString(ms.ToArray()); xml = xml.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", ""); xml = xml.Replace("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", ""); xml = Regex.Replace(xml, @"\s{2}", ""); xml = Regex.Replace(xml, @"\s{1}/>", "/>"); return xml; } } catch (Exception ex) { throw ex; } } /// <summary> /// 反序列化xml字符为对象,默认为Utf-8编码 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xml"></param> /// <returns></returns> public static T DeSerialize<T>(string xml) where T : new() { return DeSerialize<T>(xml, Encoding.UTF8); } /// <summary> /// 反序列化xml字符为对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xml"></param> /// <param name="encoding"></param> /// <returns></returns> public static T DeSerialize<T>(string xml, Encoding encoding) where T : new() { try { var mySerializer = new XmlSerializer(typeof(T)); using (var ms = new MemoryStream(encoding.GetBytes(xml))) { using (var sr = new StreamReader(ms, encoding)) { return (T)mySerializer.Deserialize(sr); } } } catch (Exception e) { return default(T); } } } Class Of XmlSerializeHelper
关于如何在C#项目中实现对象序列化XML就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。