writing xml data to sql server using sqlbulkcopy in C# asp.net

c# sqlbulkcopy sql-server xml

Question

I have two xml files on m system called customers.xml and customerdetails.xml. I am attempting to write this data directly to an sql database I created in asp.net. All of my coding is in C#. The sql database contains a table called CustomerDetails which has the fields CustomerID, CustomerN, CustomerLN, CustomerAdd, CustomerTelNo, and Comments.

In asp.net I have created a page called update which contains a upload control which I am attempting to get the xml file and write the data to the database. The code for the control is as follows:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication9
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExt == ".xml")
{
try
{
DataSet reportData = new DataSet();
SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;  
AttachDbFilename=|DataDirectory|\CustomerDetails.mdf;Integrated  
Security=True;User Instance=True");
SqlBulkCopy sbc = new SqlBulkCopy(connection);
sbc.DestinationTableName = "CustomerInfo";
connection.Open();
sbc.WriteToServer(reportData.Tables[0]);
}
catch (Exception ex)
{
 Label1.Text = "ERROR: " + ex.Message.ToString();
 }
 }
 else
 {
                Label1.Text = "Only .xml files allowed!";
            }
        }
        else
        {
            Label1.Text = "You have not specified a file.";
        }
    }
}

}

However when I attempt to get the file I am getting an error which says cannot find table [0];

Can anyone help me identify what the problem is here!!

Popular Answer

You need some way to get your XML data into the DataSet before you can call .Tables[0]. Try using the .ReadXml() function of the DataSet class to load the data into your dataset:

FROM: http://msdn.microsoft.com/en-us/library/fx29c3yd(v=VS.100).aspx

DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable("table1");
dataTable.Columns.Add("col1", typeof(string));
dataSet.Tables.Add(dataTable);

string xmlData = "<XmlDS><table1><col1>Value1</col1></table1><table1><col1>Value2</col1></table1></XmlDS>";

System.IO.StringReader xmlSR = new System.IO.StringReader(xmlData);

dataSet.ReadXml(xmlSR, XmlReadMode.IgnoreSchema);

Then you should be able to call sbc.WriteToServer(reportData.Tables[0]); no problem.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why