NewGaoKaoApi/New_College.Common/Helper/XmlSerializeHelper.cs

123 lines
3.8 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace New_College.Common
{
public class XmlSerializeHelper
{
/// <summary>
/// XML转换为对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <returns></returns>
public static T XMLToObject<T>(string xml) where T : new()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode root = doc.FirstChild;
Dictionary<string, object> table = new Dictionary<string, object>();
foreach (XmlNode v in root.ChildNodes)
{
if (v.Name == "#text")
continue;
table.Add(v.Name, GetValue(v));
}
return DicToObject<T>(table); //new RequestText(table);
}
/// <summary>
/// 字典类型转化为对象
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
private static T DicToObject<T>(Dictionary<string, object> dic) where T : new()
{
var md = new T();
DicToObject(md, dic);
return md;
}
/// <summary>
/// Dictionary填充对象
/// </summary>
/// <param name="md"></param>
/// <param name="dic"></param>
private static void DicToObject(object md, System.Collections.IDictionary dic)
{
foreach (var filed in dic.Keys)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
try
{
var value = dic[filed];
if (value is System.Collections.IDictionary)
{
Type ct = md.GetType().GetProperty(filed + "", flag).PropertyType;
object o = Activator.CreateInstance(ct);
DicToObject(o, value as System.Collections.IDictionary);
md.GetType().GetProperty(filed + "", flag).SetValue(md, o, null);
}
else
{
Type type = md.GetType();
if (type != null)
{
var pro = type.GetProperty(filed + "", flag);
if (pro != null)
pro.SetValue(md, value, null);
}
}
}
catch (Exception e)
{
}
}
// return md;
}
/// <summary>
/// 获得节点值
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private static object GetValue(XmlNode node)
{
if (node.HasChildNodes)
{
// <MsgType><![CDATA[text]]></MsgType> 这种结构 node.ChildNodes.Count==1
if (node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType != XmlNodeType.Element)
{
return node.InnerText;
}
else
{
Dictionary<string, object> table = new Dictionary<string, object>();
foreach (XmlNode n in node.ChildNodes)
{
table.Add(n.Name, GetValue(n));
}
return table;
}
}
return node.InnerText;
}
}
}