Wednesday, 28 December 2011

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.

   /// <summary>
   /// This method is used to convert the DataTable into string XML format.
   /// </summary>
   /// <param name="dtBuildSQL">DataTable to be converted.</param>
   /// <returns>(string) XML form of the DataTable.</returns>
   private static 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, XmlWriteMode.WriteSchema);
       XMLformat = sbSQL.ToString();
       return XMLformat;
   }

0 Responses to “How to convert DataTable to XML in C#”

Post a Comment