C# 从数据表创建XML
使用C:我想把这个表转换成XML。请忽略行名称中的错误。这是测试数据。我给出了两个转换为xml的列的示例,以及作为属性的相应行。但实际上我想要所有的专栏。这是一个数据表C# 从数据表创建XML,c#,xml,linq,datatable,dataset,C#,Xml,Linq,Datatable,Dataset,使用C:我想把这个表转换成XML。请忽略行名称中的错误。这是测试数据。我给出了两个转换为xml的列的示例,以及作为属性的相应行。但实际上我想要所有的专栏。这是一个数据表 <ListDataCollateralDials> <DataCollateralDials Type="Conv"> <Multiplier>1</
<ListDataCollateralDials>
<DataCollateralDials Type="Conv">
<Multiplier>1</Multiplier>
<Seasoning>1</Seasoning>
<Lockin>1</Lockin>
<Multiplier>1</Multiplier>
<ElbowShift>0</ElbowShift>
<Steepness>1</Steepness>
<Burnout>1</Burnout>
<Adjustment >1</Adjustment>
<Effect>1</Effect>
<Decay>1</Decay>
<Outs>1</Outs>
<Base>700</Base>
<Slope>1</Slope>
<Base>80</Base>
<Slope2>1</Slope2>
<Base2>200</Base2>
<Slope3>1</Slope3>
<Height>0</Height>
<Length>0</Length>
<Height2>0</Height2>
<Length2>0</Length2>
<Elbow>0</Elbow>
<Multiplier2>1</Multiplier2>
<Multiplier3>1</Multiplier3>
</DataCollateralDials>
<DataCollateralDials Type="Conv">
<Multiplier>1</Multiplier>
<Seasoning>1</Seasoning>
<Lockin>1</Lockin>
<Multiplier>1</Multiplier>
<ElbowShift>0</ElbowShift>
<Steepness>1</Steepness>
<Burnout>1</Burnout>
<Adjustment >1</Adjustment>
<Effect>1</Effect>
<Decay>1</Decay>
<Outs>1</Outs>
<Base>700</Base>
<Slope>1</Slope>
<Base>80</Base>
<Slope2>1</Slope2>
<Base2>200</Base2>
<Slope3>1</Slope3>
<Height>0</Height>
<Length>0</Length>
<Height2>0</Height2>
<Length2>0</Length2>
<Elbow>0</Elbow>
<Multiplier2>1</Multiplier2>
<Multiplier3>1</Multiplier3>
</DataCollateralDials>
</ListDataCollateralDials>
DataTables被设计为对行进行迭代,而不是像您现在这样对列进行迭代。没有任何内置功能可以按列主顺序持久化数据表。您将不得不使用自定义代码。伪代码类似于:
foeeach(DataColumn)
if(name != "Name")
output column header
foreach(DataRow)
output row value
你可以试着用这个
这对我很有效。谢谢stackoverflow。*在第二个xelement中。这是打字错误Use DataTable.WriteXml我必须跳过第一列。如果有人能给我提供代码,那就太好了。我添加了跳过“名称”列,但你必须自己做一些工作。如果你有特定的问题,你可以把它们作为新问题发布在这里,但我怀疑你是否会找人为你写下全部内容。
DataTable youdatatable = GetData();
System.IO.StringWriter writer = new System.IO.StringWriter();
youdatatable.WriteXml(writer, XmlWriteMode.WriteSchema, true);
PrintOutput(writer);
public static string ToXml(this DataTable table, int metaIndex = 0)
{
XDocument xdoc = new XDocument(
new XElement(table.TableName,
from column in table.Columns.Cast<DataColumn>()
where column != table.Columns[metaIndex]
select new XElement(column.ColumnName,
from row in table.AsEnumerable()
select new XElement(row.Field<string>(metaIndex), row[column])
)
)
);
return xdoc.ToString();
}