.Net HowTo - Saving Query results as XML

A very powerful and extremely simple tool to convert your SQL results into an XML file is the following:

    Dim objDS As New DataSet

    Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click        Dim objConn As New SqlConnection        Dim objDA As SqlDataAdapter

        Try            objConn.ConnectionString = "server=(local);database=northwind;integrated security=SSPI"            objConn.Open()            objDA = New SqlDataAdapter("SELECT * FROM customers ORDER BY companyname", objConn)            objDA.Fill(objDS, "customers")            objConn.Close()            dgData.DataSource = objDS.Tables("customers")        Catch objError As Exception            MessageBox.Show(objError.Message)        End Try    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click        Try            objDS.WriteXml("c:projectscustomers.xml")        Catch objError As Exception            MessageBox.Show(objError.Message)        End Try

Using this method you can save any table in your dataset to an XML file. This can come in handy when transfering data to clients, or even to coworkers. Not to mention to make a backup of your data before making changes.

Leave a Reply