Using C# : I want to convert this table into XML. Please ignore the mistakes in row names. This is test data. I have given sample of two columns converted to xml and the corresponding rows as attributes . But i actually want for all columns. This is a Datatable.
<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>
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();
}
This worked great for me. Thanks stackoverflow.
DataTable
s are designed to iterate over rows, not columns like you have. There's nothing built-in to persist a DataTable
in column-major order. You're going to have use custom code. Pseudo-code would be something like:
foeeach(DataColumn)
if(name != "Name")
output column header
foreach(DataRow)
output row value
you can try using this
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With