The objective of this blog is to implement bulk insert / update data from UI or Business Layers where most of the time, we use looping to insert data. For this scenario, we can convert class or List Collection into XML format. The useful thing that we need most of the times is serialization which I will implement here for generating XML.
In most of the cases, I have seen that the easiest way to convert to XML is by using the DataTable.
In most of the cases, I have seen that the easiest way to convert to XML is by using the DataTable.
- private static string ConvertDataTableToXML(DataTable dtData) {
- DataSet dsData = new DataSet();
- StringBuilder sbSQL;
- StringWriter swSQL;
- string XMLformat;
- try {
- sbSQL = new StringBuilder();
- swSQL = new StringWriter(sbSQL);
- dsData.Merge(dtData, true, MissingSchemaAction.AddWithKey);
- dsData.Tables[0].TableName = "SampleDataTable";
- foreach(DataColumn col in dsData.Tables[0].Columns) {
- col.ColumnMapping = MappingType.Attribute;
- }
- dsData.WriteXml(swSQL, XmlWriteMode.WriteSchema);
- XMLformat = sbSQL.ToString();
- return XMLformat;
- } catch (Exception sysException) {
- throw sysException;
- }
- }
After converting any DataTable, we will get the below string.
- <NewDataSet>
- <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
- <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
- <xs:complexType>
- <xs:choice minOccurs="0" maxOccurs="unbounded">
- <xs:element name="SampleDataTable">
- <xs:complexType>
- <xs:attribute name="Name" type="xs:string" />
- <xs:attribute name="Address" type="xs:string" />
- <xs:attribute name="Phone" type="xs:string" /> </xs:complexType>
- </xs:element>
- </xs:choice>
- </xs:complexType>
- </xs:element>
- </xs:schema>
- <SampleDataTable Name="Franklin" Address="Hosur" Phone="46945616" />
- <SampleDataTable Name="SAMRAj Gill" Address="DT-HOSUR" Phone="78971651" />
- </NewDataSet>
Let's remove the tag <xs:schema …..></xs:schema>. Now checking in SQL Server to open XML file and read from it. For that, we have to add the below code in Query Window and check. And, we put this in Query window of SQL Server. It will show like below.
- DECLARE @SET1 NVARCHAR(MAX)
- SET @SET1 = '<NewDataSet> < SampleDataTable Name = "Franklin"
- Address = "Hosur"
- Phone = "46945616" / > < SampleDataTable Name = "SAMRAj Gill"
- Address = "DT-HOSUR"
- Phone = "78971651" / > < /NewDataSet>'
- DECLARE @XMLDocPointer INT
- EXEC sp_xml_preparedocument @XMLDocPointer OUTPUT, @SET1
- BEGIN TRANSACTION
- --INSERT INTO dbo.some_table(ID, Name, [Address], Phone)
- select '1'
- as ID, Name, [Address], Phone
- from
- OPENXML(@XMLDocPointer, '/NewDataSet/SampleDataTable', 1) with(Name NVARCHAR(100), [Address] NVARCHAR(100), Phone NVARCHAR(100))
- EXEC sp_xml_removedocument @XMLDocPointer

Join the conversation! Your thoughts help the community grow.