Click here to Skip to main content
16,003,555 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
how to bulk insert XML data's from XML file With out Repeating the insert into statement,here i am using for each loop..how to insert all data's from XML file To SQL with single execution.

What I have tried:

C#
<pre lang="c#">  protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"user id=sa;password=ssa;database=Mohan;data source=PCTH101\PCTH101");
            con.Open();
            XmlDocument doc = new XmlDocument();
            doc.Load("d:/mohan/CHG_829_RPT_XML_PRD_SPEC_FINAL_2015-08-17-0908.xml");
            XmlNodeList nodes = doc.DocumentElement.SelectNodes("/fsxml/report/object/FSFORMULADOC");
            string docid = "", funcode = "" ,description = "" ,formulacode = "",funlabel = "";
            foreach (XmlNode node in nodes)
            {
                docid = node.SelectSingleNode("DOC_ID").InnerText;
                funcode = node.SelectSingleNode("FUNCTION_CODE").InnerText;
                description = node.SelectSingleNode("DOC_DESCRIPTION").InnerText;
                formulacode = node.SelectSingleNode("FORMULA_CODE").InnerText;
                funlabel = node.SelectSingleNode("FUNCTION_CODE_LABEL").InnerText;
                SqlCommand cmd = new SqlCommand("Insert  INTO xml1(docid,funcode,description,formulacode,funlabel) values(@docid, @funcode,@description,@formulacode,@funlabel)", con);
                cmd.Parameters.AddWithValue("@docid", docid);
                cmd.Parameters.AddWithValue("@funcode", funcode);
                cmd.Parameters.AddWithValue("@description", description);
                cmd.Parameters.AddWithValue("@formulacode", formulacode);
                cmd.Parameters.AddWithValue("@funlabel", funlabel);

                cmd.ExecuteNonQuery();
                Label1.Text = "Uploaded Successfully,Check database for Inserted Data's";
                Label1.Visible = true;


            }
Posted
Updated 21-Mar-17 20:17pm
Comments
Tomas Takac 21-Mar-17 4:00am    
In order to use SqlBulkCopy you need to wrap the XML as IDataReader. AFAIK there is nothing like an XmlDataReader in the framework. You would need to write yourself or use a third party component.

1 solution

Hi,

Do you specifically need to code it yourself? To this this quickly and repeatedly one can easily use a tool called Linx 5 without having to code. You can read the XML into the tool and get the whole data structure, which you can then write into any database you'd like (SQL, MySQL, Oracle, etc.).

You can check it out at Linx 5 - Welcome[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900