Net-informations.com
SiteMap  | About    

How to create an XML file from SQL

XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . Moreover the Dataset in ADO.NET uses XML format as its internal storage format.

There are several ways to create an XML file . In the previous sections we already saw how to create an XML file using XmlTextWriter and also created an XML file using manually created Dataset. Here we are going to create an XML file from Database. Make an SQL connection to the Database and execute the sql and store the data in a Datset. Call Dataset's WriteXml() method and pass the file name as argument.




using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient; 

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection connection );
            SqlDataAdapter adapter ;
            DataSet ds = new DataSet();
            string sql = null;

            connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password";
            connection = new SqlConnection(connetionString);
            sql = "select * from Product";
            try
            {
                connection.Open();
                adapter = new SqlDataAdapter(sql, connection);
                adapter.Fill(ds);
                connection.Close();
                ds.WriteXml("Product.xml");
                MessageBox.Show("Done");
            }
            catch (Exception ex)
            {
                MessageBox.Show (ex.ToString());

            }
        }
    }
}

You have to pass necessary database connection information to connection string.






net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.