从DataTable创建XML
使用C#:我想将此表转换为XML。 请忽略行名称中的错误 。 这是测试数据。 我已经将两列的样本转换为xml,并将相应的行作为属性。 但我实际上想要所有列。 这是一个数据表。
1 1 1 1 0 1 1 1 1 1 1 700 1 80 1 200 1 0 0 0 0 0 1 1 1 1 1 1 0 1 1 1 1 1 1 700 1 80 1 200 1 0 0 0 0 0 1 1
public static string ToXml(this DataTable table, int metaIndex = 0) { XDocument xdoc = new XDocument( new XElement(table.TableName, from column in table.Columns.Cast() where column != table.Columns[metaIndex] select new XElement(column.ColumnName, from row in table.AsEnumerable() select new XElement(row.Field(metaIndex), row[column]) ) ) ); return xdoc.ToString(); }
这对我很有用。 谢谢stackoverflow。
DataTable
旨在迭代行,而不是像您一样迭代行。 没有任何内置function可以按列主要顺序保留DataTable
。 您将使用自定义代码。 伪代码类似于:
foeeach(DataColumn) if(name != "Name") output column header foreach(DataRow) output row value
你可以尝试使用它
http://msdn.microsoft.com/en-us/library/system.data.datatable.writexml.aspx
DataTable youdatatable = GetData(); System.IO.StringWriter writer = new System.IO.StringWriter(); youdatatable.WriteXml(writer, XmlWriteMode.WriteSchema, true); PrintOutput(writer);