18

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

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Vara Prasad.M
  • 1,530
  • 9
  • 31
  • 55
  • I posted an answer here that may help: https://stackoverflow.com/questions/17868607/datatable-to-xdocument-custom You can control exactly how the XML will be built (i.e. what to store as attributes, what to name elements, what to store as child-elements, etc...). It uses `XDocument`, which you could easily code to save to a file using `XDocument.Save(FileName)`. – MikeTeeVee Jul 26 '18 at 08:22

3 Answers3

33

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);
}
Developer
  • 231
  • 4
  • 19
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • Thanks. The first method encloses a row with TABLE tags. Is there any way I could replace it with custom tags, like ROW ? Of course, I could search the string itself and replace TABLE with ROW, but I want a different approach. – Steam Dec 20 '13 at 05:28
9

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.

Ryan Castillo
  • 1,135
  • 10
  • 22
8

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);
}
kiran
  • 1,062
  • 24
  • 31