Merge pull request #352 from hudingwen/master

xml序列化内存泄漏修复
This commit is contained in:
ansonzhang 2023-10-28 18:55:49 +08:00 committed by GitHub
commit ac9fd34b58
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,33 +1,40 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace Blog.Core.Common.Helper
{
/// <summary>
/// xml序列化帮助类
/// </summary>
public class XmlHelper
{
/// <summary>
/// 存储序列类型,防止内存泄漏
/// </summary>
private static ConcurrentDictionary<Type, XmlSerializer> hasTypes = new ConcurrentDictionary<Type, XmlSerializer>();
/// <summary>
/// 转换对象为JSON格式数据
/// </summary>
/// <typeparam name="T">类</typeparam>
/// <param name="obj">对象</param>
/// <returns>字符格式的JSON数据</returns>
public static string GetXML<T>(object obj)
public static string GetXML<T>(object obj, string rootName = "root")
{
try
XmlSerializer xs;
var xsType = typeof(T);
hasTypes.TryGetValue(xsType, out xs);
if(xs == null)
{
XmlSerializer xs = new XmlSerializer(typeof(T));
using (TextWriter tw = new StringWriter())
{
xs.Serialize(tw, obj);
return tw.ToString();
}
xs = new XmlSerializer(typeof(T));
hasTypes.TryAdd(xsType, xs);
}
catch (Exception)
using (TextWriter tw = new StringWriter())
{
return string.Empty;
xs.Serialize(tw, obj);
return tw.ObjToString();
}
}
@ -37,15 +44,20 @@ namespace Blog.Core.Common.Helper
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <returns></returns>
public static T ParseFormByXml<T>(string xml,string rootName="root")
public static T ParseFormByXml<T>(string xml, string rootName = "root")
{
XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(rootName));
StringReader reader = new StringReader(xml);
T res = (T)serializer.Deserialize(reader);
reader.Close();
reader.Dispose();
return res;
}
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);
}
}
}
}