I have a DataTable which I select from database (Well, these data cross several tables, after the query and putting into a DataTable, it shows at below)
ColumnA ColumnB
a 11
b 33
b 44
a 22
b 55
but I want to transform it into an XML like this
<root>
<header name ='a'>
<item name='11' />
<item name='22' />
</header>
<header name ='b'>
<item name='33' />
<item name='44' />
<item name='55' />
</header>
</root>
Is there an easy way to implement it by C#?
OK, second approach after learning that the data is available in a
DataTableto begin with.The code is a bit more involved, since based on a DataTable, you can’t really do much in terms of grouping etc. I am building up the
XmlDocument(since you’re on .NET 2.0) while scanning through the rows of data. I need to keep track of the<header>elements in a dictionary, in order to add a second, third entry with the same “ColumnA” value to that already existingXmlElementin the document – it’s a bit involved, but if you study it carefully, I hope you see it’s really no trickery or anything – just a bit of bookkeeping along the way of building theXmlDocument: