C# 通过反射 XML 互转 Model 类

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;
                        object objA = Activator.CreateInstance(pro.PropertyType);
                        RecurveType(objA, xmlDoc, xn);
                        pro.SetValue(model, objA, null);
                    }


                }
            }
        }
    }

上一篇:防止fixed元素遮挡其他元素的方法


下一篇:数学建模-插值算法原理笔记