2012-06-06 106 views
0

我有XMl文件我正在閱讀使用此代碼的所有Xml。但意思是,我想插入XML記錄到SQL表,無論我有讀。我沒有找到任何解決方案.XMl包含沒有行,我怎樣才能以適當的方式插入。XML到SQL SERVER記錄插入

 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 
      { 

      } 
     } 
+0

那你試試? –

+0

我想插入我已經從XML讀取到SQL Server表的記錄。 –

+0

檢查答案,並不忘記upvote並將其標記爲接受,如果它適合你... –

回答

2

這裏是如何使用OPENXML功能

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


利用功能一個例子:OPENXML (Transact-SQL)這是SQL Server avialble可以讓你在服務器中插入數據... 。

也讀爲: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 
+0

有沒有其他的方法。就像閱讀我可以從vrresult直接讀取每個值。或者你可以解釋你的解決方案。 –

+0

@kuldeepverma - 你需要爲此創建過程,並且必須將xml字符串傳遞給此代碼,並在上面的代碼中xml字符串將被你的參數替換....我希望你能理解.... –

+0

Pranay Rana @我不是瞭解此代碼。在哪裏以及如何調用這個存儲過程..路徑是動態的..有很多xml文件我想根據用戶輸入插入 –