Friday, 8 June 2012

.Net Beginners , C# Tips : Generate XML File from Dataset

You can generate XML file from Dataset very easily.
Here are sample example for this.
In this example we have one dataset name "products" and one table inside dataset name "product".
We populate some records in table and generate xml from that and save this XML file using StreamWriter.

C# Example :
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        DataColumn dc;
        DataRow dr;
        ds.DataSetName = "products";
        dt.TableName = "product";

        dc = new DataColumn("product_id");
        dt.Columns.Add(dc);

        dc = new DataColumn("product_name");
        dt.Columns.Add(dc);

        dr = dt.NewRow();
        dr["product_id"] = 1;
        dr["product_name"] = "Monitor";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["product_id"] = 2;
        dr["product_name"] = "Mouse";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["product_id"] = 3;
        dr["product_name"] = "KeyBoard";
        dt.Rows.Add(dr);

        ds.Tables.Add(dt);
        string strXML= ds.GetXml();

        System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath("datasetxml.xml"));
        sw.WriteLine(strXML);
        sw.Close();

VB.net Example :
        Dim ds As New DataSet()
        Dim dt As New DataTable()
        Dim dc As DataColumn
        Dim dr As DataRow
        ds.DataSetName = "products"
        dt.TableName = "product"

        dc = New DataColumn("product_id")
        dt.Columns.Add(dc)

        dc = New DataColumn("product_name")
        dt.Columns.Add(dc)

        dr = dt.NewRow()
        dr("product_id") = 1
        dr("product_name") = "Monitor"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr("product_id") = 2
        dr("product_name") = "Mouse"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr("product_id") = 3
        dr("product_name") = "KeyBoard"
        dt.Rows.Add(dr)

        ds.Tables.Add(dt)
        Dim strXML As String = ds.GetXml()

        Dim sw As New System.IO.StreamWriter(Server.MapPath("datasetxml.xml"))
        sw.WriteLine(strXML)
        sw.Close()

Output :
<products>
  <product>
    <product_id>1</product_id>
    <product_name>Monitor</product_name>
  </product>
  <product>
    <product_id>2</product_id>
    <product_name>Mouse</product_name>
  </product>
  <product>
    <product_id>3</product_id>
    <product_name>KeyBoard</product_name>
  </product>
</products>

No comments:

Post a Comment