Tuesday, December 6, 2011

Export DataSet to XML File

create xml file from a dataset
This code snippet show how to export DataSet to xml file.Here we have taken data from database and fill dataset.We have taken a aspx page and a button there,after clicking the button a xml file will be created at specified location.

 public void CreateXml()  
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("usp_GetAddressDetails",con);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
StreamWriter objStreamWriter = new StreamWriter("E:\\Santosh\\Practices\\ASP\\XMLFiles\\EmpAddress.xml", false);
ds.WriteXml(objStreamWriter);
objStreamWriter.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateXml();
}


Regards
Santosh Singh

Monday, December 5, 2011

Insert XML data into SQL Server 2008

 protected void Button1_Click(object sender, EventArgs e)   
  {   
       string EmpCode = null;   
       string City = null;   
       string State = null;   
       string Country = null;   
       string str = null;   
       SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=Test;Integrated Security=True");   
       XmlDocument document = new XmlDocument();   
       document.Load("E:\\Santosh\\EmpAddress.xml");   
       XmlNodeList xmlNodeList = document.SelectNodes("EmpAddress/Address");   
       foreach (XmlNode node in xmlNodeList)   
       {   
            EmpCode = node["EmpCode"].InnerText;   
            City = node["City"].InnerText;   
            State = node["State"].InnerText;   
            Country = node["Country"].InnerText;   
            str = "INSERT INTO AddressDetail (EmpCode,City,State,Country) values ('" + EmpCode + "', '" + City + "','" + State + "','" + Country + "')";   
            SqlCommand cmd = new SqlCommand();   
            cmd = new SqlCommand(str, con);   
            cmd.CommandType = CommandType.Text;   
            con.Open();   
            cmd.ExecuteNonQuery();   
            con.Close();   
       }   
  }