Back to all posts
C#.NETXMLData

How to Convert DataTable to XML Programmatically

SathishMarch 5, 2010

Converting DataTable to XML is useful for data export, storage, and web services.

Simple Conversion

csharp
using System.Data;
using System.IO;

DataTable dt = GetDataTable(); // Your DataTable

// Method 1: WriteXml
dt.TableName = "Record";
StringWriter sw = new StringWriter();
dt.WriteXml(sw);
string xml = sw.ToString();

// Method 2: Save to file
dt.WriteXml("output.xml");

// Method 3: With schema
dt.WriteXml("output.xml", XmlWriteMode.WriteSchema);

Custom XML Format

csharp
public static XElement DataTableToXElement(DataTable dt)
{
    return new XElement("Records",
        from row in dt.AsEnumerable()
        select new XElement("Record",
            from col in dt.Columns.Cast<DataColumn>()
            select new XElement(col.ColumnName, row[col])
        )
    );
}

Output Example

xml
<Records>
  <Record>
    <ID>1</ID>
    <Name>John</Name>
    <Email>[email protected]</Email>
  </Record>
  <Record>
    <ID>2</ID>
    <Name>Jane</Name>
    <Email>[email protected]</Email>
  </Record>
</Records>
0claps
Share this post

Comments

Protected by reCAPTCHA v3

No comments yet. Be the first to comment.