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

XML 和 List 互转类的更多相关文章

  1. Json、JavaBean、Map、XML之间的互转

    思路是JavaBean.Map.XML都可以用工具类很简单的转换为Json,进而实现互相转换 1.Map.XML与Json互转 mvn依赖 <dependency> <groupId ...

  2. 【C#】菜单功能,将剪贴板JSON内容或者xml内容直接粘贴为类

    VS 2015菜单功能,将剪贴板JSON内容或者xml内容直接粘贴为类

  3. Xml序列化、反序列化帮助类

    之前从网络上找了一个Xml处理帮助类,并整理了一下,这个帮助类针对Object类型进行序列化和反序列化,而不需要提前定义Xml的结构,把它放在这儿供以后使用 /// <summary> / ...

  4. JavaScript实现XML与JSON互转代码(转载)

    下面来分享一个关于JavaScript实现XML与JSON互转例子,这里面介绍了国外的三款xml转json的例子,希望这些例子能给你带来帮助. 最近在开发在线XML编辑器,打算使用JSON做为中间格式 ...

  5. xml配置和基于java类的bean配置搭配使用

    如果同时使用了xml配置,和java类的bean配置(当然估计项目中一般不会这样), 在初始化容器指定资源文件的时候可能会比较麻烦 此时我们可以把基于java类的bean配置整合到xml中,或xml的 ...

  6. xml转json和实体类的两种方式

    本文为博主原创,未经允许不得转载: xml在http通信中具有较高的安全性和传输速度,所以应用比较广泛, 在项目中往往需要对xml,json和实体类进行相互转换,在这里总结一下自己所用到的一些方法: ...

  7. 利用Xml架构生成实体访问类

    由xml生成xsd及实体类   xmldataset工具 使用VS2005工具XSD.exe(SDK/v2.0/Bin/xsd.exe)自动生成实体类: xsd /c /namespace:myCom ...

  8. JAVA中 XML与数据库互转 学习笔记三

    要求 必备知识 JAVA基础知识,XML基础知识,数据库的基本操作. 开发环境 MyEclipse10/MySql5.5 资料下载 源码下载   数据库在数据查询,修改,保存,安全等方面与其他数据处理 ...

  9. 【转】Spring学习---Bean配置的三种方式(XML、注解、Java类)介绍与对比

    [原文]https://www.toutiao.com/i6594205115605844493/ Spring学习Bean配置的三种方式(XML.注解.Java类)介绍与对比 本文将详细介绍Spri ...

随机推荐

  1. 0909 45作业one

    1.编译原理学什么? 答: 初遇编译原理,我知道编译原理是计算机专业设置的一门重要的专业课程,主要是介绍编译程序构造的一般原理和基本方法.其内容大概包括语言和文法.词法分析.语法分析.语法制导翻译.中 ...

  2. NSString 的 compare 方法

    - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange ...

  3. centos 下 Qt Creator 的安装使用

    centos 下 Qt Creator 的安装使用 Qt 以其开源,免费,完全面向对象(很容易扩展),允许真正的组件编程以及可移植跨平台等诸多优势得到越来越多的开发人员的青睐.Qt Creator 是 ...

  4. Spring AOP小结

    一. AOP介绍 AOP(Aspect-OrientedProgramming,面向方面编程),可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善.OOP ...

  5. berkeley db replica机制 - 主从同步

    repmgr/repmgr_net.c, __repmgr_send(): 做send_broadcast, 然后根据policy 对DB_REP_PERMANENT的处理 __repmgr_send ...

  6. 4.2.2 网络编程之Socket

    1基于TCP协议的Socket 服务器端首先声明一个ServerSocket对象并且指定端口号,然后调用Serversocket的accept()方法接收客户端的数据.Accept()方法在没有数据进 ...

  7. [ASE][Daily Scrum]11.24

    今天开会总结了一下第一周的进度,讨论了无限地图的访存方法,做了简单的人员调整, Client的包接收分析与服务器通信这块基本上完成了, 之后Jiafan Zhu会开始和Junbei以及Songtao一 ...

  8. Debian修改ssh端口和禁止root远程登陆设置

    linux修改端口22vi /etc/ssh/sshd_config找到#port 22将前面的#去掉,然后修改端口 port 1234重启服务就OK了service sshd restart或/et ...

  9. beetle 2.7海量消息广播测试

    由于client资源限制,只进行了300物体互动广播测试:物体活动频率是每秒20次,服务器每秒转发的消息量大概180W条. 转发消息结构: class Po : IMessage { public i ...

  10. Chrome以https访问gitlab的问题:Your connection is not private

    在Chrome中以https访问自己搭建的gitlab站点时经常出现下面的错误: Attackers might be trying to steal your information from xx ...