C# 动态类型 模型转XML
<?xml version="1.0" encoding="utf-8"?> <qrylist><order orderid="1234567890"></order> <order orderid="1234567891"></order> <order orderid="1234567892"></order> </qrylist>
模型定义
public class RequestXML
{
public qrylistModel qrylist { get; set; }
public class qrylistModel
{
public ordeModel order { get; set; }
public class ordeModel
{
public string orderid { get; set; }
}
}
}
使用方法:
RequestXML requestXML = new RequestXML();
requestXML.qrylist = new RequestXML.qrylistModel();
requestXML.qrylist.order = new RequestXML.qrylistModel.ordeModel();
requestXML.qrylist.order.orderid = "123123123";
StringBuilder strbuil = new StringBuilder();
var xmlstr = XMLHelper.ModelRecurveToXML(requestXML, strbuil);
xmlstr = strbuil.Insert(0, xmlstr).ToString();
XmlDocument docReqContex = new XmlDocument();
XmlDeclaration decl = docReqContex.CreateXmlDeclaration("1.0", "utf-8", null);
docReqContex.LoadXml(xmlstr);
docReqContex.InsertBefore(decl, docReqContex.DocumentElement);
忘记看他这个xml 格式是个List 更新一下使用方法
RequestXML requestXML = new RequestXML();
requestXML.qrylist = new RequestXML.qrylistModel();
requestXML.qrylist.order = new List<RequestXML.qrylistModel.ordeModel>();
requestXML.qrylist.order.Add(new RequestXML.qrylistModel.ordeModel()
{
orderid="123123"
});
requestXML.qrylist.order.Add(new RequestXML.qrylistModel.ordeModel()
{
orderid = "44433333"
});
StringBuilder strbuil = new StringBuilder();
var xmlstr = XMLHelper.ModelRecurveToXML(requestXML, strbuil);
xmlstr = strbuil.Insert(0, xmlstr).ToString();
XmlDocument docReqContex = new XmlDocument();
XmlDeclaration decl = docReqContex.CreateXmlDeclaration("1.0", "utf-8", null);
docReqContex.LoadXml(xmlstr);
docReqContex.InsertBefore(decl, docReqContex.DocumentElement);
模型转XML 具体实现方法
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 = "")
{
if (model == null)
{
return string.Empty;
}
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
{
var val = pro.GetValue(model, null);
if (val != null)
{
suf.Insert(0, "</" + pro.Name + ">");
}
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>(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="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);
}
else
{
xlNode = xn.SelectSingleNode(pro.Name);
if (xlNode == null)
{
xlNode = GetXmlNode(xn.ChildNodes, pro.Name);
}
}
xn = xlNode;
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);
}
}
}
}
}
}
2021-05-25 重构 递归XML给模型赋值 因为list 数据时model 只能取到一条记录
/// <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 BaseType = pro.PropertyType.BaseType.Name; xn = xmlDoc.SelectSingleNode(BaseType); } 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 { 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"); foreach (XmlNode xns in xn.ChildNodes) { var ml = listPro.PropertyType; object objA = Activator.CreateInstance(ml); RecurveType(objA, xmlDoc, xns); var addMethod = modelList.GetType().GetMethod("Add"); addMethod.Invoke(modelList, new object[] { objA }); } pro.SetValue(model, modelList, null); } else { if (xn == null) { xn = xmlDoc.SelectSingleNode(pro.Name); } else { XmlNode xlNode = xn.SelectSingleNode(pro.Name); if (xlNode == null) { xlNode = GetXmlNode(xn.ChildNodes, pro.Name); } xn = xlNode; } object objA = Activator.CreateInstance(pro.PropertyType); RecurveType(objA, xmlDoc, xn); pro.SetValue(model, objA, null); } } } } }