Thursday, March 4, 2010

How to Convert Datatable to XML programmatically


Lets assume our requirement is to create a Data Table and convert it to XML format. Use the following block code for your purpose.

DataSet myDS = new DataSet();
DataTable dtMyTable = new DataTable("preview");

DataColumn myCol0 = new DataColumn("facility");
myCol0.DataType = System.Type.GetType("System.String");
myCol0.MaxLength = 256;
myCol0.AllowDBNull = true;

DataColumn myCol1 = new DataColumn("doctype");
myCol1.DataType = System.Type.GetType("System.String");
myCol1.MaxLength = 256;
myCol1.AllowDBNull = true;

dtMyTable.Columns.Add(myCol0);
dtMyTable.Columns.Add(myCol1);
dtMyTable.AcceptChanges();

DataRow myNewRow = dtMyTable.NewRow();
myNewRow["facility"] = "MyFacility Works Great!";
myNewRow["doctype"] = "MyDocType Field Does Too!";
dtMyTable.Rows.Add(myNewRow);
dtMyTable.AcceptChanges();

myDS.Tables.Add(dtMyTable);

myDS.WriteXml(Server.MapPath("~") + "\\sample.xml");


0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...