Convert DataTable to Xml and Vice-Versa
Convert DataTable to Xml and Vice-Versa
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = DtTable();
string change = ConvertDatatableToXML(dt);
DataTable dtret = ConvertXMLtoDataTable(change);
}
public string ConvertDatatableToXML(DataTable dt)
{
MemoryStream str = new MemoryStream();
dt.WriteXml(str, true);
str.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(str);
string xmlstr;
xmlstr = sr.ReadToEnd();
return (xmlstr);
}
public DataTable DtTable()
{
DataTable table = new DataTable() { TableName = "Customer" };
DataColumn keyColumn = table.Columns.Add("Id", typeof(System.Int32));
table.Columns.Add("Name", typeof(System.String));
table.Columns.Add("Address", typeof(System.String));
table.PrimaryKey = new DataColumn[] { keyColumn };
table.Rows.Add(new object[] { 1, "Customer 1", "Address1" });
table.Rows.Add(new object[] { 2, "Customer 2", "Address2" });
table.Rows.Add(new object[] { 3, "Customer 3", "Address3" });
table.Rows.Add(new object[] { 4, "Customer 4", "Address4" });
table.Rows.Add(new object[] { 5, "Customer 5", "Address5" });
table.AcceptChanges();
return table;
}
public DataTable ConvertXMLtoDataTable(string status)
{
string response = status;
DataSet ds = new DataSet();
using (StringReader stringReader = new StringReader(response))
{
ds = new DataSet();
ds.ReadXml(stringReader);
}
DataTable RetDt = ds.Tables[0];
return RetDt;
}
Comments
Post a Comment