XML到SQL SERVER记录插入

时间:2012-06-06 07:43:50

标签: c# asp.net linq linq-to-sql

我有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
            {

            }
        }

1 个答案:

答案 0 :(得分:3)

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

Bulk Insertion of Data Using C# DataTable and SQL server OpenXML function


利用函数:OPENXML (Transact-SQL)可以在sql server中使用,允许你在服务器中插入数据....

另请阅读:Use OPENXML to insert values from a string of 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