Friday, May 25, 2012

How to convert DataTable to XML in C#?

Following code illustrates about converting a DataTable to XML format. This is often required when passing a DataTable to a stored procedure. We can pass an XML directly to the procedure and process it.

private string ConvertDataTableToXML(DataTable dtBuildSQL)
{

  DataSet dsBuildSQL = new DataSet();

  StringBuilder sbSQL;
  StringWriter swSQL;
  string XMLformat;

  sbSQL = new StringBuilder();
  swSQL = new StringWriter(sbSQL);
  dsBuildSQL.Merge(dtBuildSQL, true, MissingSchemaAction.AddWithKey);
 dsBuildSQL.Tables[0].TableName = "Table";
 foreach (DataColumn col in dsBuildSQL.Tables[0].Columns)
 {
    col.ColumnMapping = MappingType.Attribute;
 }
 dsBuildSQL.WriteXml(swSQL);
 XMLformat = sbSQL.ToString();
 return XMLformat;
} 

No comments:

Post a Comment