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

write data to xml

时间:2018-03-12 18:44:49      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:ast   XML   mda   oid   nts   blog   nbsp   first   range   

 

 

        public class Student
        {
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }

        private DataTable ConvertDataToDataTable<T>(IEnumerable<T> list)
        {
            var type = typeof(T);
            var properties = type.GetProperties();
            var dataTable = new DataTable();
            dataTable.Columns.AddRange(properties.Select(x => new DataColumn(x.Name)).ToArray());
            foreach (var item in list)
            {
                var dataRow = dataTable.NewRow();
                foreach (var property in properties)
                {
                    dataRow[property.Name] = property.GetValue(item, null);
                }
                dataTable.Rows.Add(dataRow);
            }
            return dataTable;
        }

        [Test]
        public void XmlTest()
        {
            DataSet dataSet = new DataSet {DataSetName = "CustomDataSet"};
            Student student1 = new Student
            {
                Id = 1,
                FirstName = "Chuck",
                LastName = "Lu"
            };
            Student student2 = new Student()
            {
                Id = 2,
                FirstName = "Yong",
                LastName = "Zhang"
            };
            IEnumerable<Student> list = new List<Student>() { student1, student2 };
            var dataTable = ConvertDataToDataTable(list);
            dataTable.TableName = "Students";
            dataSet.Tables.Add(dataTable);
            string xml = dataSet.GetXml();
            Console.WriteLine(xml);
        }

 

输出结果为:

<CustomDataSet>
  <Students>
    <Id>1</Id>
    <FirstName>Chuck</FirstName>
    <LastName>Lu</LastName>
  </Students>
  <Students>
    <Id>2</Id>
    <FirstName>Yong</FirstName>
    <LastName>Zhang</LastName>
  </Students>
</CustomDataSet>

 

write data to xml

标签:ast   XML   mda   oid   nts   blog   nbsp   first   range   

原文地址:https://www.cnblogs.com/chucklu/p/8550183.html

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