write data to xml

Posted Chuck Lu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了write data to xml相关的知识,希望对你有一定的参考价值。

 

 

        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的主要内容,如果未能解决你的问题,请参考以下文章

[React Testing] Use Generated Data in Tests with tests-data-bot to Improve Test Maintainability(代码片段

解决gpg failed to sign the data fatal: failed to write commit object解决方案

LINQ to XML - 从文件加载 XML 片段

How to write XML-RPC clients

Greenplum Spark Connector org.postgresql.util.PSQLException: ERROR: error when writing data to gpfdi

spark write data to minio test