Wednesday 27 August 2014

Upload XML into SQL Server

Pass XML parameter to Stored Procedure in C#
In this article I  will explain how to insert data XML to SQL server.
In previous article I explain how pass XML as a parameter in stored procedure.

Now We will see how it works in ASP.NET, C#,

Sample XML:
<?xmlversion="1.0"standalone="yes"?>
<Customers>
 <CustomerId ="1">
    <Name>Sujoy Santra</Name>
    <Country>Indias</Country>
 </Customer>
 <CustomerId = "2">
    <Name>Mithun Patra</Name>
    <Country>India</Country>
 </Customer>
    <CustomerId ="3">
    <Name>Pradipta Chowdhury</Name>
    <Country>India</Country>
 </Customer>
    <CustomerId ="4">
    <Name>Sumit Kumar Sen</Name>
    <Country>India</Country>
 </Customer>
</Customers>

Take one fileuploader control and one button in ASPX page.

<asp:FileUpload ID = "FileUpload1" runat = "server" />
<asp:Button ID="Button1" Text="Upload XML" runat="server" OnClick="UploadXML" />


Write the following code in C# page:

protected void UploadXML(object sender, EventArgs e)
{
    string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
    string filePath = Server.MapPath("~/Uploads/") + fileName;
    FileUpload1.SaveAs(filePath);
    string xml = File.ReadAllText(filePath);
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("InsertXML"))
        {
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@xml", xml);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

Run the code.