当前位置: 移动技术网 > IT编程>开发语言>.net > 复杂实体转xml

复杂实体转xml

2018年08月11日  | 移动技术网IT编程  | 我要评论

湖北蕲春房价,新密五个人火了全照,尖锐湿疣口服药

 public static XElement ToXElement<T>(T entity, XElement element = null, XElement parent = null, XElement children = null) where T : new()
        {
            if (element == null) element = new XElement(entity.GetType().Name);

            PropertyInfo[] properties = entity.GetType().GetProperties();
            XElement innerElement = null;
            object propertyValue = null;

            foreach (PropertyInfo property in properties)
            {
                if (property.GetValue(entity) == null) continue;

                //当属性为字符串时
                if (property.PropertyType == typeof(string) || property.GetValue(entity).GetType() == typeof(string))
                {
                    propertyValue = property.GetValue(entity);
                    innerElement = new XElement(property.Name, propertyValue);

                    if (children != null) children.Add(innerElement);
                    else element.Add(innerElement);

                }//当该属性为List泛型时,或者为引用类型。
                else if (property.PropertyType.IsGenericType || property.PropertyType.IsClass)
                {
                    if (property.PropertyType.IsClass)
                    {
                        if (children != null) parent = children;
                        children = new XElement(property.Name);
                    }
                    else
                        children = new XElement(property.GetValue(entity).GetType().Name);

                    if (property.GetValue(entity).GetType().IsGenericType)
                    {
                        foreach (object o in (property.GetValue(entity) as IEnumerable))
                        {
                            ToXElement(o, element, parent, children);
                        }
                    }
                    else
                    {
                        return ToXElement(property.GetValue(entity), element, parent, children);
                    }
                }
                else
                {
                    propertyValue = property.GetValue(entity);
                    innerElement = new XElement(property.Name, propertyValue);

                    if (children != null) children.Add(innerElement);
                    else element.Add(innerElement);
                }
            }
            if (children != null)
            {
                if (parent != null) parent.Add(children);
                else parent = children;
                element.Add(parent);
            }
            return element;
        }

  

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网