0

我有 XML 文件,我正在使用此代码读取所有 Xml。但意思是,当我想将 XML 记录插入 sql 表时,无论我读过什么。我没有找到任何解决方案。XMl 包含行数以及如何以正确的方式插入。

       if (File.Exists(xmlpath))
          {
             try
              {
                XDocument xmlDoc = XDocument.Load(xmlpath);
                var vrresult = from a in xmlDoc.XPathSelectElements("/Parts/Part")
                               select new
                               {
                                  S  = a.Element("Section").Value,
                                   M = a.Element("Mark").Value,
                                   Q = a.Element("Qty").Value,
                                   W = a.Element("Weight").Value,
                                   RD = a.Element("databaseUpdateMark").Value

                               };
                GridView1.DataSource = vrresult;
                GridView1.DataBind();

            }
            catch (Exception ex)
            {
                Lbmsg.Text = ex.Message;
            }
            finally
            {

            }
        }
4

1 回答 1

3

这是一个如何使用 OPENXML 函数的示例

使用 C# DataTable 和 SQL server OpenXML 函数批量插入数据


利用功能:在 sql server 中可用的OPENXML (Transact-SQL)允许您在服务器中插入数据....

另请阅读:使用 OPENXML 插入 XML 字符串中的值

例子 :

--Use OPENXML to pull records from an XML string and insert them into a database

DECLARE @idoc int
DECLARE @doc varchar (1000)

--XML document

SET @doc ='
<ROOT>
    <Employee>
        <FirstName>Tom</FirstName>
        <LastName>Jones</LastName>
    </Employee>
    <Employee>
        <FirstName>Gus</FirstName>
        <LastName>Johnson</LastName>
    </Employee>
</ROOT>'

--Create an internal representation of the XML document
--the idoc variable is set as the document handler, so we can refer to it later

EXEC sp_xml_preparedocument @idoc OUTPUT, @doc

-- Use the OPENXML rowset provider with an Insert
-- @idoc lets us know which internal representation of an xml doc to use
-- '/ROOT/Employee' shows us which node in the xml tree to work on
-- the 2 denotes we want to use elemenet centric mapping for the values, as oppsed to attributes or a combination of both
-- in the 'With' we specify how the output rowset will look

INSERT INTO Employees (FirstName, LastName)
SELECT *
FROM OPENXML (@idoc, '/ROOT/Employee',2) 
WITH (FirstName varchar(10),
LastName varchar(20)
)

-- Clear the XML document from memory

EXEC sp_xml_removedocument @idoc
于 2012-06-06T07:48:59.957 回答