C# 通过反射 XML 互转 Model 类
实操
<Info xmlns=""> <Error>User 錯誤</Error> </Info>
public class ResponseModel { public class InfoModel { public string Error { get; set; } } public InfoModel Info { get; set; } }
调用
ResponseModel reqXMLData = XmlToModel<ResponseModel>(xml);
方法
/// <summary> /// XML 转Model /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Model"></param> /// <param name="xmlContent"></param> /// <param name="xmlRootName"></param> /// <returns></returns> public static T XmlToModel<T>(string xmlContent) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.XmlResolver = null; xmlDoc.LoadXml(xmlContent); object obj = Activator.CreateInstance(typeof(T)); RecurveType(obj, xmlDoc, null); return (T)obj; } /// <summary> /// 递归XML给模型赋值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> /// <param name="xmlDoc"></param> /// <param name="xn"></param> public static void RecurveType<T>(T model, XmlDocument xmlDoc, XmlNode xn) { var type = model.GetType(); foreach (System.Reflection.PropertyInfo pro in type.GetProperties()) { if ((pro.PropertyType.IsPrimitive || pro.PropertyType.IsSealed) && xn != null) { XmlElement xe = (XmlElement)xn; var val = xe.GetAttribute(pro.Name); if (string.IsNullOrWhiteSpace(val)) { XmlNode xnValue= xe.SelectSingleNode(pro.Name);
if (null != xnValue)
{
pro.SetValue(model, xnValue.InnerText, null);
} } else { pro.SetValue(model, val, null); } } else { if (pro.PropertyType.IsPrimitive || pro.PropertyType.IsSealed) { if (xn == null) { var dddddd = pro.PropertyType.BaseType.Name; var ddddd = xmlDoc.SelectSingleNode(pro.Name); } else { XmlElement xe = (XmlElement)xn; var val = xe.GetAttribute(pro.Name); if (string.IsNullOrWhiteSpace(val)) { pro.SetValue(model, xe.InnerText, null); } else { pro.SetValue(model, val, null); } } } else { XmlNode xlNode = null; if (xn == null) { xlNode = xmlDoc.SelectSingleNode(pro.Name); if (xlNode == null) { xlNode = GetXmlNode(xn.ChildNodes, pro.Name); } } else { xlNode = xn.SelectSingleNode(pro.Name); if (xlNode == null) { xlNode = GetXmlNode(xn.ChildNodes, pro.Name); } } xn = xlNode; //判断该对象是否为list var IsGenericType = pro.PropertyType.IsGenericType; var list = pro.PropertyType.GetInterface("IEnumerable", false); if (IsGenericType && list != null) { Type proType = pro.PropertyType; var modelList = Activator.CreateInstance(proType) as IEnumerable<object>; var listPro = modelList.GetType().GetProperty("Item"); var ml = listPro.PropertyType; object objA = Activator.CreateInstance(ml); RecurveType(objA, xmlDoc, xn); var addMethod = modelList.GetType().GetMethod("Add"); addMethod.Invoke(modelList, new object[] { objA }); pro.SetValue(model, modelList, null); } else { object objA = Activator.CreateInstance(pro.PropertyType); RecurveType(objA, xmlDoc, xn); pro.SetValue(model, objA, null); } } } } } /// <summary> /// 获取XML 节点 /// </summary> /// <param name="xnList"></param> /// <param name="stridr"></param> /// <returns></returns> public static XmlNode GetXmlNode(XmlNodeList xnList, string stridr) { XmlNode xn = null; foreach (XmlNode item in xnList) { xn = item.SelectSingleNode(stridr); if (xn == null) { GetXmlNode(item.ChildNodes, stridr); if (item.Name == stridr) { xn = item; } } } return xn; }
零碎的代码总结
public class XMLHelper
{
/// <summary>
/// 模型转XML文件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="suf"></param>
/// <param name="strIde"></param>
/// <returns></returns>
public static string ModelRecurveToXML<T>(T model, StringBuilder suf, string strIde = "")
{
StringBuilder builder = new StringBuilder();
System.Reflection.PropertyInfo[] proArray = model.GetType().GetProperties();
foreach (System.Reflection.PropertyInfo pro in proArray)
{
if (pro.PropertyType.IsPrimitive || pro.PropertyType.IsSealed)
{
if (string.IsNullOrWhiteSpace(strIde))
{
builder.Append(string.Format("<{0}>{1}</{2}>", pro.Name, pro.GetValue(model, null), pro.Name));
}
else
{
string value = SetXmlValue(pro.Name, pro.GetValue(model, null));
builder.Append(value);
}
}
else
{
if (!string.IsNullOrWhiteSpace(strIde))
{
string str = "<" + strIde + builder.ToString() + ">";
builder = new StringBuilder();
builder.Append(str);
strIde = string.Empty;
}
var IsGenericType = pro.PropertyType.IsGenericType;
var list = pro.PropertyType.GetInterface("IEnumerable", false);
if (IsGenericType && list != null)
{
var listVal = pro.GetValue(model, null) as IEnumerable<object>;
if (listVal == null) continue;
foreach (var aa in listVal)
{
var dtype = aa.GetType();
builder.Append(ModelRecurveToXML(aa, suf, pro.Name) + " </" + pro.Name + ">");
}
}
else
{
suf.Insert(0, "</" + pro.Name + ">");
var val = pro.GetValue(model, null);
builder.Append(ModelRecurveToXML(val, suf, pro.Name));
}
}
}
if (!string.IsNullOrWhiteSpace(strIde))
{
builder.Insert(0, "<" + strIde + "");
builder.Append(">");
}
return builder.ToString();
}
/// <summary>
/// 设置XML 值
/// </summary>
/// <param name="value"></param>
/// <param name="name"></param>
/// <returns></returns>
public static string SetXmlValue(string name, object value)
{
string str = string.Empty;
if (value != null)
{
bool inse = false;
if (value.GetType() == typeof(DateTime))
{
if (default(DateTime) != (DateTime)value)
{
inse = true;
}
}
else if (value.GetType() == typeof(string))
{
inse = true;
}
else if (value.GetType() == typeof(int))
{
if (default(int) != (int)value)
{
inse = true;
}
}
else if (value.GetType() == typeof(decimal))
{
if (default(decimal) != (decimal)value)
{
inse = true;
}
}
else if (value.GetType() == typeof(double))
{
if (default(double) != (double)value)
{
inse = true;
}
}
if (inse)
{
str = string.Format(" {0}='{1}'", name, value);
}
}
return str;
}
/// <summary>
/// XML 转Model
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Model"></param>
/// <param name="xmlContent"></param>
/// <param name="xmlRootName"></param>
/// <returns></returns>
public static T XmlToModel<T>(T Model, string xmlContent, string xmlRootName)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.XmlResolver = null;
xmlDoc.LoadXml(xmlContent);
object obj = Activator.CreateInstance(Model.GetType());
RecurveType(obj, xmlDoc, null);
return (T)obj;
}
/// <summary>
/// 获取XML 节点
/// </summary>
/// <param name="xnList"></param>
/// <param name="stridr"></param>
/// <returns></returns>
public static XmlNode GetXmlNode(XmlNodeList xnList, string stridr)
{
XmlNode xn = null;
foreach (XmlNode item in xnList)
{
xn = item.SelectSingleNode(stridr);
if (xn == null)
{
GetXmlNode(item.ChildNodes, stridr);
if (item.Name == stridr)
{
xn = item;
}
}
}
return xn;
}
/// <summary>
/// 递归XML给模型赋值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="xmlDoc"></param>
/// <param name="xn"></param>
public static void RecurveType<T>(T model, XmlDocument xmlDoc, XmlNode xn)
{
var type = model.GetType();
foreach (System.Reflection.PropertyInfo pro in type.GetProperties())
{
if ((pro.PropertyType.IsPrimitive || pro.PropertyType.IsSealed) && xn != null)
{
XmlElement xe = (XmlElement)xn;
var val = xe.GetAttribute(pro.Name);
if (string.IsNullOrWhiteSpace(val))
{
pro.SetValue(model, xe.InnerText, null);
}
else
{
pro.SetValue(model, val, null);
}
}
else
{
if (pro.PropertyType.IsPrimitive || pro.PropertyType.IsSealed)
{
if (xn == null)
{
var dddddd = pro.PropertyType.BaseType.Name;
var ddddd = xmlDoc.SelectSingleNode(pro.Name);
}
else
{
XmlElement xe = (XmlElement)xn;
var val = xe.GetAttribute(pro.Name);
if (string.IsNullOrWhiteSpace(val))
{
pro.SetValue(model, xe.InnerText, null);
}
else
{
pro.SetValue(model, val, null);
}
}
}
else
{
XmlNode xlNode = null;
if (xn == null)
{
xlNode = xmlDoc.SelectSingleNode(pro.Name);
if (xlNode == null)
{
xlNode = GetXmlNode(xn.ChildNodes, pro.Name);
}
}
else
{
xlNode = xn.SelectSingleNode(pro.Name);
if (xlNode == null)
{
xlNode = GetXmlNode(xn.ChildNodes, pro.Name);
}
}
xn = xlNode;
//判断该对象是否为list
var IsGenericType = pro.PropertyType.IsGenericType;
var list = pro.PropertyType.GetInterface("IEnumerable", false);
if (IsGenericType && list != null)
{
Type proType = pro.PropertyType;
var modelList = Activator.CreateInstance(proType) as IEnumerable<object>;
var listPro = modelList.GetType().GetProperty("Item");
var ml = listPro.PropertyType;
object objA = Activator.CreateInstance(ml);
RecurveType(objA, xmlDoc, xn);
var addMethod = modelList.GetType().GetMethod("Add");
addMethod.Invoke(modelList, new object[] { objA });
pro.SetValue(model, modelList, null);
}
else
{
object objA = Activator.CreateInstance(pro.PropertyType);
RecurveType(objA, xmlDoc, xn);
pro.SetValue(model, objA, null);
}
}
}
}
}
}
第二次整理 model 互转 XML
public class XmlHelper { public static XmlElement LuoCreateXmlElement(XmlDocument thisValue, string content, string str) { XmlElement x1 = thisValue.CreateElement(str); x1.InnerText = DataConversionType.ConvertString(string.IsNullOrWhiteSpace(content.Trim()) ? "" : content.Trim(), DataConversionType.StringTypeEnum.繁); return x1; } /// <summary> /// 读取文件,返回相应字符串 /// </summary> /// <param name="fileName">文件路径</param> /// <returns>返回文件内容</returns> public static string ReadFile(string fileName) { StringBuilder str = new StringBuilder(); using (FileStream fs = File.OpenRead(fileName)) { StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("Big5")); string line = ""; while ((line = streamReader.ReadLine()) != null) { string encGi5 = Encoding.GetEncoding("Big5").GetString(System.Text.Encoding.GetEncoding("Big5").GetBytes(line.Trim())); if (!string.IsNullOrWhiteSpace(encGi5)) { str = str.Append(encGi5); } } } return str.ToString(); } /// <summary> /// XML 转Model /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Model"></param> /// <param name="xmlContent"></param> /// <param name="xmlRootName"></param> /// <returns></returns> public static T XmlToModel<T>(string xmlContent) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.XmlResolver = null; xmlDoc.LoadXml(xmlContent); object obj = Activator.CreateInstance(typeof(T)); RecurveType(obj, xmlDoc, null); return (T)obj; } /// <summary> /// 设置XML 值 /// </summary> /// <param name="value"></param> /// <param name="name"></param> /// <returns></returns> public static object SetXmlValue(Type objType, object value) { if (value != null) { if (objType == typeof(DateTime)) { return Convert.ToDateTime(value); } else if (objType == typeof(string)) { return Convert.ToString(value); } else if (objType == typeof(int)) { return Convert.ToInt32(value); } else if (objType == typeof(Int64)) { return Convert.ToInt64(value); } else if (objType == typeof(decimal)) { return Convert.ToDecimal(value); } else if (objType == typeof(double)) { return Convert.ToDouble(value); } else if (objType == typeof(bool)) { return Convert.ToBoolean(value); } } return value; } /// <summary> /// 递归XML给模型赋值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> /// <param name="xmlDoc"></param> /// <param name="xn"></param> public static void RecurveType<T>(T model, XmlDocument xmlDoc, XmlNode xn) { var type = model.GetType(); foreach (System.Reflection.PropertyInfo pro in type.GetProperties()) { if ((pro.PropertyType.IsPrimitive || pro.PropertyType.IsSealed) && xn != null) { XmlElement xe = (XmlElement)xn; var val = xe.GetAttribute(pro.Name); if (string.IsNullOrWhiteSpace(val)) { XmlNode xnValue = xe.SelectSingleNode(pro.Name); if (null != xnValue) { pro.SetValue(model, SetXmlValue(pro.PropertyType, xnValue.InnerText), null); } } else { pro.SetValue(model, val, null); } } else { if (pro.PropertyType.IsPrimitive || pro.PropertyType.IsSealed) { if (xn == null) { XmlNode xlNode = xmlDoc.SelectSingleNode(pro.Name); if (xlNode == null) { xlNode = GetXmlNode(xmlDoc.ChildNodes, pro.Name); } } else { XmlElement xe = (XmlElement)xn; var val = xe.GetAttribute(pro.Name); if (string.IsNullOrWhiteSpace(val)) { pro.SetValue(model, xe.InnerText, null); } else { pro.SetValue(model, val, null); } } } else { XmlNode xlNode = null; if (xn == null) { xlNode = xmlDoc.SelectSingleNode(pro.Name); if (xlNode == null) { xlNode = GetXmlNode(xn.ChildNodes, pro.Name); } } else { xlNode = xn.SelectSingleNode(pro.Name); if (xlNode == null) { xlNode = xmlDoc.SelectSingleNode(pro.Name); if (xlNode == null) { xlNode = GetXmlNode(xmlDoc.ChildNodes, pro.Name); } } } xn = xlNode; //判断该对象是否为list var IsGenericType = pro.PropertyType.IsGenericType; var list = pro.PropertyType.GetInterface("IEnumerable", false); if (IsGenericType && list != null) { Type proType = pro.PropertyType; var modelList = Activator.CreateInstance(proType) as IEnumerable<object>; var listPro = modelList.GetType().GetProperty("Item"); var ml = listPro.PropertyType; object objA = Activator.CreateInstance(ml); RecurveType(objA, xmlDoc, xn); var addMethod = modelList.GetType().GetMethod("Add"); addMethod.Invoke(modelList, new object[] { objA }); pro.SetValue(model, modelList, null); } else { object objA = Activator.CreateInstance(pro.PropertyType); RecurveType(objA, xmlDoc, xn); pro.SetValue(model, objA, null); } } } } } /// <summary> /// 获取XML 节点 /// </summary> /// <param name="xnList"></param> /// <param name="stridr"></param> /// <returns></returns> public static XmlNode GetXmlNode(XmlNodeList xnList, string stridr) { XmlNode xn = null; foreach (XmlNode item in xnList) { xn = item.SelectSingleNode(stridr); if (xn == null) { xn = GetXmlNode(item.ChildNodes, stridr); } if (xn != null) { break; } } return xn; } public static StringBuilder ModelRecurveToXML<T>(T model, StringBuilder builder) { StringBuilder builder3 = new StringBuilder(); foreach (System.Reflection.PropertyInfo pro in model.GetType().GetProperties()) { if (pro.PropertyType.IsPrimitive || pro.PropertyType.IsSealed) { builder.Append(string.Format("<{0}>{1}<{2}>", pro.Name, pro.GetValue(model, null), pro.Name)); } else { var IsGenericType = pro.PropertyType.IsGenericType; var list = pro.PropertyType.GetInterface("IEnumerable", false); if (IsGenericType && list != null) { builder.Append(string.Format("<{0}", pro.Name)); var listVal = pro.GetValue(model, null) as IEnumerable<object>; if (listVal == null) continue; StringBuilder listBuilder = new StringBuilder(); foreach (var aa in listVal) { var dtype = aa.GetType(); foreach (var bb in dtype.GetProperties()) { listBuilder.Append(string.Format(" {0}={1}", bb.Name, bb.GetValue(aa, null))); } } builder.Append(string.Format("{0}></{1}>", listBuilder, pro.Name)); } else { builder3.Insert(0, string.Format("</{0}>", pro.Name)); builder.Append(string.Format("<{0}", pro.Name)); StringBuilder builder2 = new StringBuilder(); foreach (var item in pro.GetValue(model, null).GetType().GetProperties()) { if (item.PropertyType.IsPrimitive || item.PropertyType.IsSealed) { builder2.Append(string.Format(" {0}={1}", item.Name, item.GetValue(pro.GetValue(model, null), null))); } else { builder.Append(string.Format(">")); builder3.Insert(0, string.Format("</{0}>", item.Name)); builder.Append(string.Format("<{0}", item.Name)); var data2 = item.GetValue(pro.GetValue(model, null), null); foreach (var item2 in data2.GetType().GetProperties()) { if (item2.PropertyType.IsPrimitive || item2.PropertyType.IsSealed) { builder2.Append(string.Format(" {0}={1}", item2.Name, item2.GetValue(data2, null))); } else { builder3.Insert(0, string.Format("</{0}>", item2.Name)); } } } } builder.Append(string.Format("{0}>", builder2.ToString())); } } } builder.Append(builder3); return builder; } /// <summary> /// XML 转Model /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Model"></param> /// <param name="xmlContent"></param> /// <param name="xmlRootName"></param> /// <returns></returns> public static T XmlToModel<T>(T Model, string xmlContent, string xmlRootName) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.XmlResolver = null; xmlDoc.LoadXml(xmlContent); object obj = Activator.CreateInstance(Model.GetType()); RecurveType(obj, xmlDoc, null); return (T)obj; } /// <summary> /// 模型转XML文件 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> /// <param name="suf"></param> /// <param name="strIde"></param> /// <returns></returns> public static string ModelToXML<T>(T model) where T : class, new() { StringBuilder builder = new StringBuilder(); System.Reflection.PropertyInfo[] proArray = model.GetType().GetProperties(); foreach (System.Reflection.PropertyInfo pro in proArray) { if (pro.PropertyType.IsPrimitive || pro.PropertyType.IsSealed) { builder.Append(string.Format("<{0}>{1}</{2}>", pro.Name, pro.GetValue(model, null), pro.Name)); } else { var IsGenericType = pro.PropertyType.IsGenericType; var list = pro.PropertyType.GetInterface("IEnumerable", false); if (IsGenericType && list != null) { var listVal = pro.GetValue(model, null) as IEnumerable<object>; if (listVal == null) continue; foreach (var item in listVal) { var objValue = item; if (objValue == null) { objValue = System.Activator.CreateInstance(objValue.GetType()); } string str = string.Format("<{0}>{1}</{2}>", pro.Name, ModelToXML(objValue), pro.Name); builder.Append(str); } } else { var objValue = pro.GetValue(model, null); if (objValue == null) { objValue = System.Activator.CreateInstance(pro.PropertyType); } string str = string.Format("<{0}>{1}</{2}>", pro.Name, ModelToXML(objValue), pro.Name); builder.Append(str); } } } return builder.ToString(); } }