Sunday, January 25, 2015

DataTable to XML C#

Datatable to XML

If you have a datatable and want to convert to XML the C# code is as follows

StringWriter writer = new StringWriter();
 dt.WriteXml(writer);

writer will have the xml.

for ex: if your datatable is in the following structue.

ID, FirstName,LastName then the above code will produce the XML in the following format.

<Table>
      <ID>1</ID>
      <FirstName>Bob</FirstName>
     </LastName>Burger</LastName>
</Table>


If you want the string Table to be replaced with something else give a name to the datatable

dataTable.TableName="StudentInfo"; then the xml will be as follows.

<StudentInfo>
      <ID>1</ID>
      <FirstName>Bob</FirstName>
     </LastName>Burger</LastName>
</StudentInfo>

if you want the XML schema along with the xml then use the following.

dt.WriteXml(writer, XmlWriteMode.WriteSchema, true);
.. what this does is adds the schema at the top.


Thanks,
Bob


No comments:

Post a Comment