XML 和 List 互转类

XML 和 List 互转类

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace XmlHelper
{
     ///   <summary>
    
///  实体转Xml,Xml转实体类
    
///   </summary>
    
///   <typeparam name="T"></typeparam>
     public  class XmlHelper<T>  where T :  new()
    {
         #region 实体类转成Xml
         ///   <summary>
        
///  对象实例转成xml
        
///   </summary>
        
///   <param name="item"> 对象实例 </param>
        
///   <returns></returns>
         public  static  string EntityToXml(T item)
        {
            IList<T> items =  new List<T>();
            items.Add(item);
             return EntityToXml(items);
        }

         ///   <summary>
        
///  对象实例集转成xml
        
///   </summary>
        
///   <param name="items"> 对象实例集 </param>
        
///   <returns></returns>
         public  static  string EntityToXml(IList<T> items)
        {
             // 创建XmlDocument文档
            XmlDocument doc =  new XmlDocument();
             // 创建根元素
            XmlElement root = doc.CreateElement( typeof(T).Name +  " s ");
             // 添加根元素的子元素集
             foreach (T item  in items)
            {
                EntityToXml(doc, root, item);
            }
             // 向XmlDocument文档添加根元素
            doc.AppendChild(root);

             return doc.InnerXml;
        }

         private  static  void EntityToXml(XmlDocument doc, XmlElement root, T item)
        {
             // 创建元素
            XmlElement xmlItem = doc.CreateElement( typeof(T).Name);
             // 对象的属性集

            System.Reflection.PropertyInfo[] propertyInfo =
             typeof(T).GetProperties(System.Reflection.BindingFlags.Public |
            System.Reflection.BindingFlags.Instance);



             foreach (System.Reflection.PropertyInfo pinfo  in propertyInfo)
            {
                 if (pinfo !=  null)
                {
                     // 对象属性名称
                     string name = pinfo.Name;
                     // 对象属性值
                     string value = String.Empty;

                     if (pinfo.GetValue(item,  null) !=  null)
                        value = pinfo.GetValue(item,  null).ToString(); // 获取对象属性值
                    
// 设置元素的属性值
                    xmlItem.SetAttribute(name, value);
                }
            }
             // 向根添加子元素
            root.AppendChild(xmlItem);
        }


         #endregion

         #region Xml转成实体类

         ///   <summary>
        
///  Xml转成对象实例
        
///   </summary>
        
///   <param name="xml"> xml </param>
        
///   <returns></returns>
         public  static T XmlToEntity( string xml)
        {
            IList<T> items = XmlToEntityList(xml);
             if (items !=  null && items.Count >  0)
                 return items[ 0];
             else  return  default(T);
        }

         ///   <summary>
        
///  Xml转成对象实例集
        
///   </summary>
        
///   <param name="xml"> xml </param>
        
///   <returns></returns>
         public  static IList<T> XmlToEntityList( string xml)
        {
            XmlDocument doc =  new XmlDocument();
             try
            {
                doc.LoadXml(xml);
            }
             catch
            {
                 return  null;
            }
             if (doc.ChildNodes.Count !=  1)
                 return  null;
             if (doc.ChildNodes[ 0].Name.ToLower() !=  typeof(T).Name.ToLower() +  " s ")
                 return  null;

            XmlNode node = doc.ChildNodes[ 0];

            IList<T> items =  new List<T>();

             foreach (XmlNode child  in node.ChildNodes)
            {
                 if (child.Name.ToLower() ==  typeof(T).Name.ToLower())
                    items.Add(XmlNodeToEntity(child));
            }

             return items;
        }

         private  static T XmlNodeToEntity(XmlNode node)
        {
            T item =  new T();

             if (node.NodeType == XmlNodeType.Element)
            {
                XmlElement element = (XmlElement)node;

                System.Reflection.PropertyInfo[] propertyInfo =
             typeof(T).GetProperties(System.Reflection.BindingFlags.Public |
            System.Reflection.BindingFlags.Instance);

                 foreach (XmlAttribute attr  in element.Attributes)
                {
                     string attrName = attr.Name.ToLower();
                     string attrValue = attr.Value.ToString();
                     foreach (System.Reflection.PropertyInfo pinfo  in propertyInfo)
                    {
                         if (pinfo !=  null)
                        {
                             string name = pinfo.Name.ToLower();
                            Type dbType = pinfo.PropertyType;
                             if (name == attrName)
                            {
                                 if (String.IsNullOrEmpty(attrValue))
                                     continue;
                                 switch (dbType.ToString())
                                {
                                     case  " System.Int32 ":
                                        pinfo.SetValue(item, Convert.ToInt32(attrValue),  null);
                                         break;
                                     case  " System.Boolean ":
                                        pinfo.SetValue(item, Convert.ToBoolean(attrValue),  null);
                                         break;
                                     case  " System.DateTime ":
                                        pinfo.SetValue(item, Convert.ToDateTime(attrValue),  null);
                                         break;
                                     case  " System.Decimal ":
                                        pinfo.SetValue(item, Convert.ToDecimal(attrValue),  null);
                                         break;
                                     case  " System.Double ":
                                        pinfo.SetValue(item, Convert.ToDouble(attrValue),  null);
                                         break;
                                     default:
                                        pinfo.SetValue(item, attrValue,  null);
                                         break;
                                }
                                 continue;
                            }
                        }
                    }
                }
            }
             return item;
        }

         #endregion
    }

 

XML转List

List转XML

Model转XML

XML转Model 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Java实现实体列表和JSON之间的互转换可以使用Jackson或Gson库。这里提供使用Jackson库的示例代码。 首先,需要在Maven或Gradle中添加Jackson库的依赖项。例如,在Maven中,可以将以下依赖项添加到pom.xml文件中: ```xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.0</version> </dependency> ``` 然后,定义一个实体Person: ```java public class Person { private String name; private int age; // getters and setters } ``` 接下来,将Person对象列表转换为JSON格式: ```java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws JsonProcessingException { List<Person> personList = new ArrayList<>(); personList.add(new Person("John", 30)); personList.add(new Person("Jane", 25)); ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(personList); System.out.println(json); } } ``` 输出结果为: ``` [{"name":"John","age":30},{"name":"Jane","age":25}] ``` 最后,将JSON格式转换回Person对象列表: ```java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; public class Main { public static void main(String[] args) throws Exception { String json = "[{\"name\":\"John\",\"age\":30},{\"name\":\"Jane\",\"age\":25}]"; ObjectMapper objectMapper = new ObjectMapper(); List<Person> personList = objectMapper.readValue(json, new TypeReference<List<Person>>() {}); System.out.println(personList); } } ``` 输出结果为: ``` [Person{name='John', age=30}, Person{name='Jane', age=25}] ``` 注意:在将实体转换为JSON格式时,实体必须有无参构造函数和getter/setter方法。在将JSON格式转换回实体时,必须确保JSON格式正确,否则可能会抛出异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值