C# 实体类序列化与反序列化二 (DataContractSerializer)

网友投稿 594 2022-11-13

C# 实体类序列化与反序列化二 (DataContractSerializer)

C# 实体类序列化与反序列化二 (DataContractSerializer)

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.Serialization;using System.IO;using System.Xml;namespace Common.Utility.XMLSerialization{ ///

/// DataContractSerializer /// /// public class DataContractSerializer { /// /// 实体序列化成xml string /// /// /// public static string ToXMLString(T meta) { DataContractSerializer dcs = new DataContractSerializer(typeof(T)); string xmlStr = string.Empty; using (MemoryStream ms = new MemoryStream()) { try { dcs.WriteObject(ms, meta); xmlStr = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); } catch { throw; } } return xmlStr; } /// /// DataContract序列化 /// /// /// 已知类型的集合 /// public static string ToXMLString(object value, IEnumerable knownTypes = null) { try { DataContractSerializer dataContractSerializer = new DataContractSerializer(value.GetType(), knownTypes); using (MemoryStream ms = new MemoryStream()) { dataContractSerializer.WriteObject(ms, value); ms.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(ms)) { return sr.ReadToEnd(); } } } catch { throw; } } /// /// 实体反序列化 /// /// /// public static T ReadFromXML(string xmlStr) { T meta; try { DataContractSerializer dcs = new DataContractSerializer(typeof(T)); using (TextReader reader = new StringReader(xmlStr)) { using (XmlReader xReader = XmlReader.Create(reader)) { meta = (T)dcs.ReadObject(xReader); } } } catch { throw; } return meta; } /// /// 实体反序列化 /// /// /// IEnumerable /// public static T ReadFromXML(string xmlStr, IEnumerable knownTypes = null) { T meta; try { DataContractSerializer dcs = new DataContractSerializer(typeof(T), knownTypes); using (TextReader reader = new StringReader(xmlStr)) { using (XmlReader xReader = XmlReader.Create(reader)) { meta = (T)dcs.ReadObject(xReader); } } } catch { throw; } return meta; } }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:如何让Activiti-Explorer使用sql server数据库
下一篇:SpringBoot Security的自定义异常处理
相关文章

 发表评论

暂时没有评论,来抢沙发吧~