十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
这篇文章给大家介绍如何在C#项目中实现对象序列化XML,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
成都创新互联2013年至今,先为沈丘等服务建站,沈丘等地企业,进行企业商务咨询服务。为沈丘企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。首先,需要用到的是这两个命名空间(主要)
using System.Xml; using System.Xml.Serialization;
然后序列化和反序列化的方式和Json一样。(后面提供封装方法)
string result = XmlSerializeHelper.Serialize(new test { name = "Seven", cardId = "663927", age = 15, currentTime = DateTime.Now }); Console.WriteLine(result); test test2 = XmlSerializeHelper.DeSerialize (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 obj) { return Serialize (obj, Encoding.UTF8); } /// /// 实体对象序列化成xml字符串 /// ////// /// public static string Serialize (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; } } /// /// 反序列化xml字符为对象,默认为Utf-8编码 /// ////// /// public static T DeSerialize (string xml) where T : new() { return DeSerialize (xml, Encoding.UTF8); } /// /// 反序列化xml字符为对象 /// ////// /// /// public static T DeSerialize (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就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。