As we know we can connect to the SQL server and we can display the table in DataGridview. Sometimes we require to generate XML file and XML Schema Definition files based on database. Today we discuss about how to connect to SQL server and how to generate XML, XSD files from this data.
Open Microsoft Visual Studio => Create new Windows Application project. Create Company Database and Employee table in SQL Server.
Now connect to this Company Database and Fetch the Employee details as shown below.
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;
namespace CreateXMLFromDB
{
public partial class Form1 : Form
{
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
}
private void btnDB_Click(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection("Data Source=MSSQLSERVER2008;Initial Catalog=Company;user id=sa;password=dlog24");
SqlDataAdapter sqlDad = new SqlDataAdapter("SELECT * FROM Employee", sqlCon);
sqlDad.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
private void btnExcel_Click(object sender, EventArgs e)
{
string fileName1 = @"E:\XML\Employee.xml";
string fileName2 = @"E:\XML\Employee.xsd";
if (ds.Tables.Count == 0)
{
MessageBox.Show("Please click on \"Get Data From DB \" button to generate XML");
}
else
{
FileStream fs1 = File.Open(fileName1, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
FileStream fs2 = File.Open(fileName2, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
ds.WriteXml(fs1);
fs1.Close();
ds.WriteXmlSchema(fs2);
fs2.Close();
MessageBox.Show("XML Files are generated successfully");
}
}
}
}
As shown above in btnDB click event, we are connecting to Company database and displaying Employee details in the DataGridView dataGridView1. In btnExcel click event, we are creating XML, XSD files in E drive XML folder. Once creating the XML and XSD files, write the dataset ds data to these files by using DataSet WriteXML, WriteXMLSchema methods.
Execute the application and the output is as shown below.