写了两个扩展方法。一个把DataTable转为XElement,一个把XElement转为DataTable。
主要用于存储少量数据。本来想弄个全面的增删改查,但我处理的数据量小,也没必要了。
总之,这样就能把xml文件的内容读到DataTable中,然后再DataTable中一通各种变形,最后再写到xml文件中了。
DataTable转XElement测试
XElement转DataTable测试
最后是两个方法的源码
1 public static DataTable ToDataTable(this XDocument xDoc, string sheetName) 2 { 3 //拿到表【sheetName】 4 var curSheet = from sheet in xDoc.Root.Elements() where sheet.Attribute("SheetName").Value == sheetName select sheet; 5 var dt = new DataTable(); 6 var head = from ele in curSheet.Elements() where ele.Name == "Head" select ele; 7 //循环写dt表头名,字段类型 8 foreach (var ele in head.Elements()) 9 { 10 var typeString = ele.Attribute("Type").Value; 11 dt.Columns.Add(ele.Value, Type.GetType(typeString)); 12 } 13 var data = from ele in curSheet.Elements() where ele.Name == "Data" select ele; 14 //循环写dt中的数据 15 foreach (var ele in data.Elements()) 16 { 17 dt.Rows.Add(ele.Elements().Select(s => s.Value).ToArray()); 18 } 19 return dt; 20 } 21 22 public static XElement ToXmlSheet(this DataTable dt,string sheetName) 23 { 24 //添加表元素 25 var aNewSheet = new XElement("XmlSheet", new XAttribute("SheetName",sheetName), 26 new XElement("Head"), 27 new XElement("Data") 28 ); 29 //写Head元素 30 var head = aNewSheet.Element("Head"); 31 foreach (DataColumn column in dt.Columns) 32 { 33 head.Add(new XElement("Field", column.ToString(), new XAttribute("Type", column.DataType.ToString()))); 34 } 35 //写Data元素 36 var data = aNewSheet.Element("Data"); 37 foreach (DataRow row in dt.Rows) 38 { 39 var curRow = new XElement("Row"); 40 var cells = row.ItemArray.Select(c => new XElement("Cell", c)); 41 foreach (var cell in cells) 42 { 43 curRow.Add(cell); 44 } 45 data.Add(curRow); 46 } 47 return aNewSheet; 48 }
时间: 2024-10-14 04:07:21