even though there are many examples out there, i can’t find what I need? My question is simply just as the title “How to convert datatable to xml” …
Although, you can suggest solution in any technology, but i have a starting point as well, please have a look at this code.
Dim xmlDoc As New XDocument(
New XElement("Class",
From row In dt.AsEnumerable()
Select New XElement("PUPIL",
New XAttribute("FIRSTNAME", row.Field(Of String)("First Name")),
New XAttribute("LASTNAME", row.Field(Of String)("Last Name")),
New XAttribute("DOB", row.Field(Of String)("DoB")),
New XAttribute("YEAR", row.Field(Of String)("Year")),
New XAttribute("SEX", row.Field(Of String)("Gender")),
New XAttribute("CLASSNAME", row.Field(Of String)("Reg"))
)))))
In this example, I need to know how many columns and the name of the columns to do the convertion. I hate to hardcode the columns name into that Linq, is it possible to do in Linq with any number of columns and column names ??
If someone can just suggest me to improve that Linq to handle any columns from the datatable that would be great.
Thanks alot.
LINQ Solution …
Dim xmlDoc As New XDocument(
From row In dt.Rows
Select New XElement("Pupil",
From column In dt.Columns
Select
New XAttribute(column.ToString, row.Item(column.ToString))))
For Datatable.WriteXML solution, please refer to Habib’s post
Instead of LINQ you can use: DataTable.WriteXML();
If you want to read and write data according to Schema do the following step:
Try the following code
In your case you can modify the schema to your need and then you can use the XML Schema to generate documents from Dataset to XML. You have to save the datatable in the dataset first. (I am not too sure about this approach, but since I have seen no new replies to this question, I thought it may be helpful to you)