欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

复杂实体转xml

程序员文章站 2024-01-17 17:28:16
多层实体转xml,泛型转xml都可用,完善中.... ......
 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;
        }