How to generate XML from DataTable and DataSet
WriteXML() and WriteXMLSchema() function associated with DataTable and DataSet
In this article we will see how to use
WriteXML() and WriteXMLSchema() associated with DataTable And DataSet in C#.
WriteXML() using DataSet and
DataTable()
In below example we will
see how to transfer DataSet data to XML file. Here is sample exampleusing System;
using System.Collections;
using System.Globalization;
using System.Data.SqlClient;
using System.Data;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Roll", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Surname", typeof(string));
dt.Rows.Add(1, "sourav", "Kayal");
dt.Rows.Add(1, "aa", "bb");
dt.Rows.Add(1, "cc", "dd");
ds.Tables.Add(dt);
ds.WriteXml(@"D:\\test.xml");
Console.ReadLine();
}
}
}
Here is
sample output:

WriteXML() with DataTable.
We can use DataTable also to generate
XML file. The procedure is same as DataSet.
staticcvoid Main(string[]cargs)
{
DataSetcds = new DataSet();
DataTablec dt = new DataTable();
dt.Columns.Add("Roll", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Surname", typeof(string));
dt.Rows.Add(1, "sourav", "Kayal");
dt.Rows.Add(1, "aa", "bb");
dt.Rows.Add(1, "cc", "dd");
dt.WriteXml("D:\\text.txt");
Console.ReadLine();
}
The output result will be same as
DataSet.
WriteXMLSchema() function with DataSet
WriteXMLSchema() function is used to
store schema only from DataSet or DataTable. In below we will see how to use
WriteXMLSchema() function with DataSet.
using System;
using System.Collections;
using System.Globalization;
using System.Data.SqlClient;
using System.Data;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Roll", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Surname", typeof(string));
dt.Rows.Add(1, "sourav", "Kayal");
dt.Rows.Add(1, "aa", "bb");
dt.Rows.Add(1, "cc", "dd");
ds.Tables.Add(dt);
ds.WriteXmlSchema(@"D:\\test.xml");
Console.ReadLine();
}
}
}
Here is
sample output

Same operation we can do with
DataTable
static void Main(string[] args)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Roll", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Surname", typeof(string));
dt.Rows.Add(1, "sourav", "Kayal");
dt.Rows.Add(1, "aa", "bb");
dt.Rows.Add(1, "cc", "dd");
dt.WriteXmlSchema(@"D:\\test.xml");
Console.ReadLine();
}
Output will be same as above output.