SQL To XML

Certain times we need to export our grid data or our custom query data to xml format.
.Net provides a very easy way to that , The two data object i.e. Dataset and DataTable has built-in overloads to do this.

public void WriteSQLToXML()
        {
 using (SqlConnection con = new SqlConnection(“server=your_sql_server_name;Database=your_db_name;Integrated Security=true;”))
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
using (SqlCommand cm = new SqlCommand(“Select * from your_table_name” , con))
                {
using (SqlDataAdapter DA = new SqlDataAdapter(cm))
                    {
                        DataSet DS = new DataSet(“mytable”);
                        DA.Fill(DS, “mytable”);


    //for winforms
   string _path = Application.StartupPath + “myData.xml”;


   //for webform
   string _path = Server.MapPath(“”) + “\\myData.xml”;


//it will save myData.xml to your local root directory of your application
                       
DS.WriteXml(_path);
                    }
                }
                
            }
        }

Leave a Reply

Your email address will not be published. Required fields are marked *