Showing posts with label datatable. Show all posts
Showing posts with label datatable. Show all posts

Tuesday, December 29, 2015

Convert DataSet and DataTable to Xml String

In this article I am going to explain how to convert DataTable or DataSet in Xml.

Convert DataTable to XML

public static string ToStringAsXml(DataSet ds)
    {
        StringWriter sw = new StringWriter();
        ds.WriteXml(sw, XmlWriteMode.IgnoreSchema);
        string s = sw.ToString();
        return s;
    }

Convert DataSet to XML

public static string ToStringAsXml(DataTable dt)
    {
        StringWriter sw = new StringWriter();
        dt.WriteXml(sw, XmlWriteMode.IgnoreSchema);
        string s = sw.ToString();
        return s;
 
    }


In the given below code , I write to data tables function CreateTable() and CreateTable1() that return table and by using that table we convert into xml. The "string dtXml" accepts xml of data table  and "string dsxml" accepts the data set xml.

Code

using System;
using System.Data;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
        DataTable dt = CreateTable();
        dt.TableName="Employee";
        string dtXml = ToStringAsXml(dt);
 
 
        DataTable dt1 = CreateTable();
        dt1.TableName = "Employee1";
 
        DataSet ds = new DataSet();
 
        ds.Tables.Add(dt);
        ds.Tables.Add(dt1);
 
        string dsxml = ToStringAsXml(ds);
      
 
    }
 
 
    public DataTable CreateTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Age");
 
        DataRow rr = dt.NewRow();
        rr["Name"] = "Sharad";
        rr["Age"] = 25;
 
        dt.Rows.Add(rr);
 
        DataRow rr1 = dt.NewRow();
        rr1["Name"] = "Devesh";
        rr1["Age"] = 25;
 
        dt.Rows.Add(rr1);
        return dt;
    }
 
    public DataTable CreateTable1()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Age");
 
        DataRow rr = dt.NewRow();
        rr["Name"] = "Sharad";
        rr["Age"] = 25;
 
        dt.Rows.Add(rr);
 
        DataRow rr1 = dt.NewRow();
        rr1["Name"] = "Devesh";
        rr1["Age"] = 25;
 
        dt.Rows.Add(rr1);
        return dt;
    }
 
 
    public static string ToStringAsXml(DataSet ds)
    {
        StringWriter sw = new StringWriter();
        ds.WriteXml(sw, XmlWriteMode.IgnoreSchema);
        string s = sw.ToString();
        return s;
    }
 
    public static string ToStringAsXml(DataTable dt)
    {
        StringWriter sw = new StringWriter();
        dt.WriteXml(sw, XmlWriteMode.IgnoreSchema);
        string s = sw.ToString();
        return s;
 
    }
}