how to transfer xml file data to database using SqlDataAdapter Update method

Imteyazkhan374
Posted by Imteyazkhan374 under C# category on | Points: 40 | Views : 1310
Sometimes we need to transfer the xml file information to the database. Here I have developed code which will transfer xml file information to the database using SqlDataAdater update method.

1. Very first you need to create a xml file like this:
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<Detail>
<Name>Imteyaz</Name>
<Age>20</Age>
<Address>Kurjee</Address>
</Detail>
<Detail>
<Name>Ehtesham</Name>
<Age>34</Age>
<Address>Patna</Address>
</Detail>
</NewDataSet>


using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Xml;
namespace XML_file_to_database_new
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataSet sqlds;
DataSet xmlds;
SqlDataAdapter da;

private void btnupdate_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=master;Integrated Security=True;");
con.Open();
da = new SqlDataAdapter(new SqlCommand("select * from detail_student", con));
SqlCommandBuilder cmdbilder = new SqlCommandBuilder(da);
sqlds = new DataSet();
da.Fill(sqlds);
xmlds = new DataSet();
xmlds.ReadXml("c:\\student.xml");

for (int i = 0; i < xmlds.Tables[0].Rows.Count; i++)
{
DataRow dr;
dr = sqlds.Tables[0].NewRow();
dr[0] = Convert.ToString(xmlds.Tables[0].Rows[i].ItemArray[0]);
dr[1] = Convert.ToInt32(xmlds.Tables[0].Rows[i].ItemArray[1]);
dr[2] = Convert.ToString(xmlds.Tables[0].Rows[i].ItemArray[2]);
sqlds.Tables[0].Rows.Add(dr);

}

da.Update(sqlds);
dataGridView1.DataSource = sqlds.Tables[0];
}
}
}

Comments or Responses

Login to post response