using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; namespace EntrustSettle.Common.Helper { /// /// xml序列化帮助类 /// public class XmlHelper { /// /// 存储序列类型,防止内存泄漏 /// private static ConcurrentDictionary hasTypes = new ConcurrentDictionary(); /// /// 转换对象为JSON格式数据 /// /// /// 对象 /// 字符格式的JSON数据 public static string GetXML(object obj, string rootName = "root") { XmlSerializer xs; var xsType = typeof(T); hasTypes.TryGetValue(xsType, out xs); if(xs == null) { xs = new XmlSerializer(typeof(T)); hasTypes.TryAdd(xsType, xs); } using (TextWriter tw = new StringWriter()) { xs.Serialize(tw, obj); return tw.ObjToString(); } } /// /// Xml格式字符转换为T类型的对象 /// /// /// /// public static T ParseFormByXml(string xml, string rootName = "root") { XmlSerializer xs; var xsType = typeof(T); hasTypes.TryGetValue(xsType, out xs); if (xs == null) { xs = new XmlSerializer(xsType, new XmlRootAttribute(rootName)); hasTypes.TryAdd(xsType, xs); } using (StringReader reader = new StringReader(xml)) { return (T)xs.Deserialize(reader); } } } }