首页 > 其他 > 详细

xml转实体类的实现

时间:2018-09-17 11:08:35      阅读:298      评论:0      收藏:0      [点我收藏+]

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转实体类的实现

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!