How to upload XML File in Asp.Net

Description:-
Here we will see how to upload xml file and save in server folder for storing data in server side.

HTML CODE:

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

STYLE SHEET:

<style type="text/css">
   body
   {
   font-family: Arial;
   font-size: 10pt;
   }
   table
   {
   border: 1px solid #ccc;
   }
   table th
   {
   background-color: #F7F7F7;
   color: #333;
   font-weight: bold;
   }
   table th, table td
   {
   padding: 5px;
   border-color: #ccc;
   }
</style>

STORE PROCEDURE:

ALTER PROCEDURE [dbo].[InsertXML]
@xml XML
AS
BEGIN
      SET NOCOUNT ON;

      INSERT INTO CustomerDetails
      SELECT
      Customer.value('@Id','INT') AS Id, --ATTRIBUTE
      Customer.value('(Name/text())[1]','VARCHAR(100)') AS Name, --TAG
      Customer.value('(Country/text())[1]','VARCHAR(100)') AS Country --TAG
      FROM
      @xml.nodes('/Customers/Customer')AS TEMPTABLE(Customer)
END

CODE BEHIND:

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["DBCS"].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();
        }
    }
}

Now run your Webpage and Upload XML file.

Related Posts

Previous
Next Post »

Thanks for comments.....