Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a DataTable to an XML file in C#?

I want to convert a DataTable to an XML file in C#. How can I do this?

like image 909
Vara Prasad.M Avatar asked Mar 10 '11 12:03

Vara Prasad.M


3 Answers

You can use DataTable.WriteXml Method.

Here is an example;

How can i convert my datatable into XML using C# 2.0?

string result;
using (StringWriter sw = new StringWriter()) {
dataTable.WriteXml(sw);
result = sw.ToString();
}

If you don't actually need a string but read-only, processable XML, it's a better idea to use MemoryStream and XPathDocument:

XPathDocument result;
using (MemoryStream ms = new MemoryStream()) {
dataTable.WriteXml(ms);
ms.Position = 0;
result = new XPathDocument(ms);
}
like image 69
Soner Gönül Avatar answered Oct 29 '22 00:10

Soner Gönül


You can use the writeXML method to save it as XML (Source).

You can also use serialization/desirialization as described in the fifth post of this forum.

like image 45
Ryan Castillo Avatar answered Oct 28 '22 22:10

Ryan Castillo


Another way to get this done is by adding the data table to dataset and calling the GetXml() on the dataset.In addition to this dataset is equipped with the WriteXml() and ReadXml() for writing/reading the XML directly to/from a file path or stream.

DataSet ds = new DataSet();
ds.Tables.Add(dt1); // Table 1
ds.Tables.Add(dt2); // Table 2...
...
string dsXml= ds.GetXml();
...
using (StreamWriter fs = new StreamWriter(xmlFile)) // XML File Path
{
      ds.WriteXml(fs);
}
like image 8
kiran Avatar answered Oct 28 '22 22:10

kiran