• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#通过反射XML互转Model类

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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);
                        }
                    }


                }
            }
        }
    }


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#FluentFTP类上传下载文件发布时间:2022-07-10
下一篇:
C#委托的介绍(delegate、Action、Func、predicate)发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap