Skip to content

Commit

Permalink
Merge pull request #352 from hudingwen/master
Browse files Browse the repository at this point in the history
xml序列化内存泄漏修复
  • Loading branch information
anjoy8 committed Oct 28, 2023
2 parents f6cee97 + 1b7d13a commit ac9fd34
Showing 1 changed file with 32 additions and 20 deletions.
52 changes: 32 additions & 20 deletions Blog.Core.Common/Helper/XmlHelper.cs
Original file line number Diff line number Diff line change
@@ -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();
}
}

Expand All @@ -37,15 +44,20 @@ public static string GetXML<T>(object obj)
/// <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);
}
}
}
}

0 comments on commit ac9fd34

Please sign in to comment.