How to create an XML file from SQL

XML serves as a versatile and widely adopted tag-based language, facilitating seamless transfer and storage of data across diverse applications. The .NET technology embraces XML as a widely supported file format, and within the .NET Framework, developers can use a comprehensive set of classes tailored for reading, writing, and performing various operations on XML-formatted files. Additionally, the Dataset component in ADO.NET utilizes XML as its internal storage format, further underscoring the significance of XML within the .NET ecosystem and emphasizing its key role in managing data effectively.

XML file from SQL

There are multiple approaches available for creating an XML file. In the preceding sections, we explored the creation of an XML file using XmlTextWriter and manually generated Dataset. In this scenario, our focus is on generating an XML file from a database. To achieve this, we establish an SQL connection to the database, execute the SQL query, and store the retrieved data in a Dataset. Subsequently, we invoke the WriteXml() method of the Dataset, passing the desired file name as an argument. This process allows for the seamless conversion of database content into an XML file, facilitating efficient data management and interchange.

Full Source C#
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.