July 20, 2009

Populating a SQL Server Table with data from XML

Writing values from XML file to a SQL server table.
Our xml file be “Test.xml”



Add the using directive
Using System.Data.SqlClient;
Then write the following code:



Here I am using the sql server express as the database.And the database name is “db2”.
For copying data from xml to sql server table here I am using SqlBulkCopy.
For this you should have same field names in both the cases, but if you have different names then we can map them as follows
bkc.ColumnMappings.Add("Sr_no", "SerialNum");
bkc.ColumnMappings.Add("Name", "FirstName");
bkc.ColumnMappings.Add("City", "City")


where bkc.ColumnMappings.Add(xmlfield,tablefield)
and the column names are case sensitive. i.e if you type”city” instead of “City” then it will throw runtime error “The given ColumnMapping does not match up with any column in the source or destination.”

No comments: