Try this:

DECLARE @input XML = '<dataset> 
 <metadata>
  <item name="NAME_LAST" type="xs:string" length="62" /> 
  <item name="NAME_FIRST" type="xs:string" length="62" /> 
  <item name="NAME_MIDDLE" type="xs:string" length="32" />
 </metadata>
<data>
<row>
 <value>SMITH</value> 
 <value>MARY</value> 
 <value>N</value> 
</row>
<row>
 <value>SMITH2</value> 
 <value>MARY2</value> 
 <value>N2</value> 
</row>
</data>
</dataset>'

INSERT INTO dbo.YourTable(ColName, ColFirstName, ColOther)
   SELECT
      Name = XCol.value('(value)[1]','varchar(25)'),
      FirstName = XCol.value('(value)[2]','varchar(25)'),
      OtherValue = XCol.value('(value)[3]','varchar(25)')
   FROM 
      @input.nodes('/dataset/data/row') AS XTbl(XCol)
Answer from marc_s on Stack Overflow
Top answer
1 of 2
33

Try this:

DECLARE @input XML = '<dataset> 
 <metadata>
  <item name="NAME_LAST" type="xs:string" length="62" /> 
  <item name="NAME_FIRST" type="xs:string" length="62" /> 
  <item name="NAME_MIDDLE" type="xs:string" length="32" />
 </metadata>
<data>
<row>
 <value>SMITH</value> 
 <value>MARY</value> 
 <value>N</value> 
</row>
<row>
 <value>SMITH2</value> 
 <value>MARY2</value> 
 <value>N2</value> 
</row>
</data>
</dataset>'

INSERT INTO dbo.YourTable(ColName, ColFirstName, ColOther)
   SELECT
      Name = XCol.value('(value)[1]','varchar(25)'),
      FirstName = XCol.value('(value)[2]','varchar(25)'),
      OtherValue = XCol.value('(value)[3]','varchar(25)')
   FROM 
      @input.nodes('/dataset/data/row') AS XTbl(XCol)
2 of 2
9
Insert XML Data into sql Server table

Declare @retValue1 varchar(50);
Declare @XmlStr XML;
SET @XmlStr='<Customers>
 <customer>
    <ID>111589</ID>
    <FirstName>name1</FirstName>
    <LastName>Lname1</LastName>
    <Company>ABC</Company>
  </customer>
  <customer>
    <ID>12345</ID>
    <FirstName>name2</FirstName>
    <LastName>Lname2</LastName>
    <Company>ABC</Company>
  </customer>
  <customer>
    <ID>14567</ID>
    <FirstName>name3</FirstName>
    <LastName>Lname3</LastName>
    <Company>DEF</Company>
  </customer>
</Customers>';

@retValue='Failed';
 
INSERT INTO  test_xmlinsert
SELECT
COALESCE([Table].[Column].value('ID[1]', 'int'),0) as 'ID',
[Table].[Column].value('FirstName [1]', 'varchar(50)') as ' FirstName ',
[Table].[Column].value(' LastName[1]', 'varchar(50)') as ' LastName',
[Table].[Column].value(' Company [1]', 'varchar(50)') as ' Company'
 FROM @XmlStr.nodes('/ Customers / customer') as Table
IF(@@ROWCOUNT > 0 )
  SET @retValue='SUCCESS';
🌐
SQLServerCentral
sqlservercentral.com › forums › topic › importing-an-xml-file-into-a-sql-table
Importing an XML file into a sql table – SQLServerCentral Forums
February 17, 2019 - --------------------------------------- ... is what i am trying to achieve but as im new to XML its hardd putting this into words. ... INSERT INTO XMLwithOpenXML(XMLData, LoadedDateTime) SELECT CONVERT(XML, BulkColumn) AS BulkColumn, GETDATE() FROM OPENROWSET(BULK 'C:\Scripts\ice...
Discussions

sql server - Insert XML File into specific sql table - Database Administrators Stack Exchange
I have the following xml document 12 123 الهدف More on dba.stackexchange.com
🌐 dba.stackexchange.com
INSERT XML into SQL Server 2008 database - Stack Overflow
Hello I'm trying to insert some XML data into a table on SQL Server 2008. However I keep getting thrown this error; XML parsing: line 1, character 39, unable to switch the encoding The database ... More on stackoverflow.com
🌐 stackoverflow.com
How to insert XML data into SQL Server table using XmlTextReader in C# console app? - Stack Overflow
I have a 4GB XML file. Some of its values I have to insert into a table in the database. I wrote a stored procedure and the code in the c# console but it is not inserting the data into the database... More on stackoverflow.com
🌐 stackoverflow.com
July 12, 2018
XML data into SQL Tables
Hi, I have a xml in C# code and has to store in sql table (4 tables). what is best way to insert xml records in tables send XML string to Stored procedure and there we store xml data into multiple tables? using SQL bulk copy in c# and store it… More on learn.microsoft.com
🌐 learn.microsoft.com
3
0
February 24, 2021
🌐
C# Corner
c-sharpcorner.com › blogs › insert-xml-data-in-database-using-stored-procedure-in-sql-server
Insert XML Data In Database Using Stored Procedure In SQL Server
March 24, 2018 - Let's create a Temp Table with the name #tblXMLData to store XML Data. In this Table, I will take 4 columns with name EmployeNum, EmployeName, Designation and Department Name. ... Now, let's create a procedure for inserting XML Data into #tblXMLData ...
🌐
MSSQLTips
mssqltips.com › home › importing and processing data from xml files into sql server tables
Importing and Processing data from XML files into SQL Server tables
February 24, 2022 - Import XML data from an XML file into SQL Server table using the OPENROWSET function ... I have an XML file downloaded from my FTP location to a local folder and data in this XML file looks like below. You can download the sample data here.
🌐
C# Corner
c-sharpcorner.com › article › how-to-insert-bulk-records-into-sql-server-using-xml-data-type
How To Insert Bulk Records Into SQL Server Using XML Data Type
March 10, 2018 - Create user defined type in database and send your whole table to this type. SQL query can read every record and perform insert action to the database. Using XML data type, pass XML to the database.
🌐
ASPSnippets
aspsnippets.com › questions › 184246 › Insert-XML-data-in-SQL-Table-using-C-and-VBNet-in-ASPNet
Insert XML data in SQL Table using C and VBNet in ASPNet
May 23, 2019 - <asp:Button ID="Button1" Text="Upload XML" runat="server" OnClick="UploadXML" /> <br /> <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="CustomerId" HeaderText="CustomerId" /> <asp:BoundField DataField="Name" HeaderText="Name" /> <asp:BoundField DataField="Country" HeaderText="Country" /> </Columns> </asp:GridView> ... using System.Data; using System.Configuration; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Xml;
Find elsewhere
🌐
C# Corner
c-sharpcorner.com › article › bulk-insert-update-xml-data-into-sql-table
Bulk Insert, Update XML Data Into SQL Table
September 15, 2018 - Now user would like to update old data & if the record does not into a table then insert that record. Here I am using @EmployeeXML_Old XML to insert data which contains some records and @EmployeeXML contains updated data as well as new data, I am using match condition to update the data as well as insert the data. ... Summary In this article, we learned Bulk Insert, Update XML data into SQL Table.
🌐
MSSQLTips
mssqltips.com › home › simple way to import xml data into sql server with t-sql
Simple way to Import XML Data into SQL Server with T-SQL
February 25, 2022 - This function is native to T-SQL. It allows us to read data from many different file types through the BULK import feature, which allows the import from lots of file types, like XML. Here is the code to read the XML file and to INSERT the data into a table.
🌐
Microsoft Learn
learn.microsoft.com › en-us › sql › t-sql › xml › insert-xml-dml
insert (XML DML) - SQL Server | Microsoft Learn
December 17, 2024 - In the example, you first create a table (T) with a typed xml column, in the AdventureWorks database. You then copy a manufacturing instructions XML instance from the Instructions ...
🌐
T-SQL Tutorial
tsql.info › xml › insert-xml-into-sql-table.php
Insert XML into SQL table in SQL Server - T-SQL Tutorial
Create a table in SQL Server that has a column of data type XML to store the XML data. For example, let's create a table called MyXmlTable with a single column called XmlData of type XML: ... Prepare the XML data that you want to insert into the table. You can either write the XML data directly ...
🌐
Microsoft Learn
learn.microsoft.com › en-us › sql › relational-databases › xml › load-xml-data
Load XML data - SQL Server | Microsoft Learn
March 20, 2023 - INSERT INTO T SELECT 10, xCol FROM (SELECT * FROM OPENROWSET (BULK 'C:\MyFile\xmlfile.xml', SINGLE_BLOB) AS xCol) AS R(xCol); SQL Server stores XML data in Unicode (UTF-16). XML data retrieved from the server comes out in UTF-16 encoding.
🌐
Devart
devart.com › dbforge › sql › data-pump › import-from-xml-to-sql-server.html
Import XML File into SQL Server - using Data Pump
If you select a new table as a target data source, only the Append mode can be used. ... Optionally, you can select the Use a single transaction and Use bulk insert checkboxes, the latter of which reduces the quantity of statements and speeds ...
Top answer
1 of 2
1
            using (XmlTextReader reader = new XmlTextReader("D:\\test.xml"))
            {
                while (reader.Read())
                {
                    SqlCommand insertCommand = new SqlCommand("spInsertimiListes", conn);

                    if (reader.IsStartElement("Name_details"))
                    {
                        first_name = " ";
                        middle_name = " ";
                        surname = " ";
                        gender = " ";
                        occ_title = " ";

                        while(reader.Read() && reader.IsStartElement())
                        {
                            switch(reader.Name)
                            {
                                case "FirstName":
                                    first_name = reader.ReadString();
                                    break;
                                case "MiddleName":
                                    middle_name = reader.ReadString();
                                    break;
                                case "Surname":
                                    surname = reader.ReadString();
                                    break;
                                case "Gender":
                                    gender = reader.ReadString();
                                    break;
                                case "OccTitle":
                                    occ_title = reader.ReadString();
                                    break;
                                default:
                                    throw new InvalidExpressionException("Unexpected tag");
                            }
                            reader.ReadEndElement();
                        }
                    }

                    insertCommand.CommandType = CommandType.StoredProcedure;

                    insertCommand.Parameters.AddWithValue("FirstName", first_name);
                    insertCommand.Parameters.AddWithValue("MiddleName", middle_name);
                    insertCommand.Parameters.AddWithValue("Surname", surname);
                    insertCommand.Parameters.AddWithValue("Gender", gender);
                    insertCommand.Parameters.AddWithValue("OccTitle", occ_title);

                    if (!((first_name == " " && surname == " " && middle_name == " " && gender == " " && occ_title == " ")))
                    {
                        insertCommand.ExecuteNonQuery();
                    }
                }
            }
2 of 2
0

The problem is reader.read() will read only the root node and there is only one node, so it won't move to next node. You should be navigating to child nodes by using ReadToDescendant method. The below code might work for you. Check my comments in the code.

          using (XmlTextReader reader = new XmlTextReader("D:\\test.xml"))
                {
                    reader.ReadToFollowing("Person"); // it will read the first node
                    if (reader.ReadToDescendant("Name_details")) // it will read the first descendent of Person
                    {
                        do
                        {
                            SqlCommand insertCommand = new SqlCommand("spInsertimiListes", conn);

                            if (reader.IsStartElement())
                            {
                                first_name = " ";
                                middle_name = " ";
                                surname = " ";
                                gender = " ";
                                occ_title = " ";

                                foreach (var item in reader.Name)
                                {
                                    if (reader.Name == "FirstName")
                                    {
                                        first_name = reader.ReadString();
                                    }
                                    else if (reader.Name == "MiddleName")
                                    {
                                        middle_name = reader.ReadString();
                                    }
                                    else if (reader.Name == "Surname")
                                    {
                                        surname = reader.ReadString();
                                    }
                                    else if (reader.Name == "Gender")
                                    {
                                        gender = reader.ReadString();
                                    }
                                    else if (reader.Name == "OccTitle")
                                    {
                                        occ_title = reader.ReadString();
                                    }
                                }
                            }

                            insertCommand.CommandType = CommandType.StoredProcedure;

                            insertCommand.Parameters.AddWithValue("FirstName", first_name);
                            insertCommand.Parameters.AddWithValue("MiddleName", middle_name);
                            insertCommand.Parameters.AddWithValue("Surname", surname);
                            insertCommand.Parameters.AddWithValue("Gender", gender);
                            insertCommand.Parameters.AddWithValue("OccTitle", occ_title);

                            if (!((first_name == " " & surname == " " & middle_name == " " & gender == " " & occ_title == " ")))
                            {
                                insertCommand.ExecuteNonQuery();
                            }
                        } while (reader.ReadToNextSibling("Name_details")); // it will read next descendent of person
                    }
                }
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 286730 › xml-data-into-sql-tables
XML data into SQL Tables - Microsoft Q&A
February 24, 2021 - All this starting from SQL Server 2005 onwards. And their implementation has nothing to do with the .Net Framework APIs. There are multiple ways how to handle your objective: SSIS via its XML Source Adapter. SQLXML API. T-SQL and XQuery. ... Here is a conceptual T-SQL and XQuery example how to load hierarchical XML into a one-to-many relational database tables.
🌐
SQL Shack
sqlshack.com › working-with-xml-data-in-sql-server
Working with XML Data in SQL Server
October 11, 2019 - XML is one of the most popular data formats for information exchange. In this article, we saw how we can create a document using XML from a SQL table. We also saw how to import into a table in SQL from an XML document.
🌐
C# Corner
c-sharpcorner.com › blogs › insert-xml-data-into-sql-server1
Insert XML data into SQL Server
May 3, 2012 - We couldn't retrieve the text content. Possibly it's a huge drawback with this filestream datatype. create table XMLData(id int identity(1,1),xmlFileName varchar(100),xml_data xml,o