Skip to main content

Converts a ADO.NET DataSet to an XML String.

void Main()
{
    DataTable dt = new DataTable("table");
    dt.Columns.Add("roomCode");
    dt.Columns.Add("roomNo");
    dt.Columns.Add("hotelCode");

    DataRow dr;

    dr = dt.NewRow();
    dr["roomCode"] = "1";
    dr["roomNo"] = "MKavs";
    dr["hotelCode"] = "222";

    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr["roomCode"] = "2";
    dr["roomNo"] = "232";
    dr["hotelCode"] = "33";

    dt.Rows.Add(dr);

    DataSet ds = new DataSet("dataSet");
    ds.Tables.Add(dt);

    string dataSetAsXmlStr = DataSetToXmlString(ds);

    Console.Write(dataSetAsXmlStr);
}

// Define other methods and classes here
private static string DataSetToXmlString(DataSet ds)
{
    var sb = new StringBuilder();

    using (var tw = new XmlTextWriter(new StringWriter(sb)))
    {
        tw.Formatting = Formatting.Indented;
        ds.WriteXml(tw);
        tw.Close();
    }

    return sb.ToString();
}

// ========================================================
// OUTPUT
// ========================================================
//      <dataSet>
//        <table>
//          <roomCode>1</roomCode>
//          <roomNo>MKavs</roomNo>
//          <hotelCode>222</hotelCode>
//        </table>
//        <table>
//          <roomCode>2</roomCode>
//          <roomNo>232</roomNo>
//          <hotelCode>33</hotelCode>
//        </table>
</dataSet>