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>