forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXmlHelper.cs
More file actions
63 lines (61 loc) · 1.97 KB
/
XmlHelper.cs
File metadata and controls
63 lines (61 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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, 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();
}
}
/// <summary>
/// Xml格式字符转换为T类型的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <returns></returns>
public static T ParseFormByXml<T>(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);
}
}
}
}