码迷,mamicode.com
首页 > 其他好文 > 详细

xml转实体类的实现

时间:2018-09-17 11:44:04      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:entity   ati   using   内容   serialize   main   实体类   方法   color   

1、定义方法

        public static T DESerializerStringToEntity<T>(string strXML) where T : class
        {
            try
            {
                using (StringReader sr = new StringReader(strXML))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

 

2、xml内容如下:

<request>
    <Id>11</Id>
    <Name>科技集团</Name>
    <Employees>
        <Employee>
                <Id>22</Id>
                <Name>张三</Name>
        </Employee>
        <Employee>
                <Id>22</Id>
                <Name>张三</Name>
        </Employee>
    </Employees>
</request>

3、实体类如下:

    [Serializable]
    [XmlRoot("request")]
    public class Company
    {
        public int Id { get; set; }
        public string Name { get; set; }
        [XmlArray("Employees"), XmlArrayItem("Employee")]
        public List<Employee> Employees { get; set; }
    }


    [XmlRoot(ElementName = "Employee")]
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

 

4、调用

        static void Main(string[] args)
        {
            string strXml = "<request><Id>11</Id><Name>科技集团</Name><Employees><Employee><Id>22</Id><Name>张三</Name></Employee><Employee><Id>22</Id><Name>张三</Name></Employee></Employees></request>";

            Company Com = DESerializerStringToEntity<Company>(strXml);
        }

 

xml转实体类的实现

标签:entity   ati   using   内容   serialize   main   实体类   方法   color   

原文地址:https://www.cnblogs.com/wjx-blog/p/9660859.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!