2013-10-10 54 views
0

這裏是我的xml文件:約節省的XDocument到SQL Server XML列

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://mfisoft.ru/soap" xmlns:ns2="http://xml.apache.org/xml-soap" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> 
    <SOAP-ENV:Body> 
    <ns1:selectRowsetResponse> 
     <result SOAP-ENC:arrayType="ns2:Map[1]" xsi:type="SOAP-ENC:Array"> 
     <item xsi:type="ns2:Map"> 
      <item> 
      <key xsi:type="xsd:string">report_id</key> 
      <value xsi:type="xsd:string">246</value> 
      </item> 
     </item> 
     </result> 
    </ns1:selectRowsetResponse> 
    </SOAP-ENV:Body> 
</SOAP-ENV:Envelope> 

,這是我在SQL Server表

CREATE TABLE [dbo].[HowToSaveXML](
    [ID] [int] NOT NULL, 
    [XMLcontent] [xml] NOT NULL 
) 

當我寫在SQL Server Management Studio中這樣的SQL命令

insert into HowToSaveXML values (5,'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://mfisoft.ru/soap" xmlns:ns2="http://xml.apache.org/xml-soap" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> 
    <SOAP-ENV:Body> 
    <ns1:selectRowsetResponse> 
     <result SOAP-ENC:arrayType="ns2:Map[1]" xsi:type="SOAP-ENC:Array"> 
     <item xsi:type="ns2:Map"> 
      <item> 
      <key xsi:type="xsd:string">report_id</key> 
      <value xsi:type="xsd:string">246</value> 
      </item> 
     </item> 
     </result> 
    </ns1:selectRowsetResponse> 
    </SOAP-ENV:Body> 
</SOAP-ENV:Envelope>') 

它工作正常,併成功地向表中添加一條記錄HowToSaveXML

,但是當我使用C#代碼做同樣的事情,就像這樣:

XDocument xd = XDocument.Load(@"D:\temp\0919\sDocumentToXML.xml"); 

    sqlCmdUpdate = new SqlCommand("insert into HowToSaveXML values (5 , " + xd.ToString(), conn); 

    sqlCmdUpdate.CommandTimeout = 200; 
    if (conn.State == ConnectionState.Closed) 
     conn.Open(); 
    try 
    { 
     sqlCmdUpdate.ExecuteNonQuery(); 
    } 
    catch (Exception aep) 
    { 

    } 

其中sDocumentToXML.xml包含上面的文件相同的內容,但它拋出一個異常:

Incorrect syntax near '<'. 
The label 'xmlns' has already been declared. Label names must be unique within a query batch or stored procedure 

它似乎系統不允許重複節點,但我已經成功地插入相同的XML通過使用插入命令直接在管理工作室,那麼是什麼原因,我怎樣才能使用C#代碼做同樣的事情?謝謝。

加:如果我改變這樣

sqlCmdUpdate = new SqlCommand("insert into HowToSaveXML values (5 , '" + xd.ToString() + "'", conn); 

C#代碼,它也拋出一個異常。

回答