簡體   English   中英

使用TSQL檢索XML節點值?

[英]Retrieving an XML node value with TSQL?

我什么不來? 除了NULL之外,我什么也沒有得到。

DECLARE @xml xml
SELECT @xml = '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <SOAP-ENV:Body>
    <webregdataResponse>
      <result>0</result>
      <regData />
      <errorFlag>99</errorFlag>
      <errorResult>Not Processed</errorResult>
    </webregdataResponse>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>'

DECLARE @nodeVal int
SELECT @nodeVal =  @xml.value('(errorFlag)[1]', 'int')
SELECT @nodeVal

解決方法如下:

DECLARE @xml xml
SELECT @xml = '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <SOAP-ENV:Body>
    <webregdataResponse>
      <result>0</result>
      <regData />
      <errorFlag>99</errorFlag>
      <errorResult>Not Processed</errorResult>
    </webregdataResponse>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>'


declare @table table (data xml);
insert into @table values (@xml);

WITH xmlnamespaces (
'http://schemas.xmlsoap.org/soap/envelope/' as [soap])
SELECT Data.value('(/soap:Envelope/soap:Body/webregdataResponse/errorFlag)[1]','int') AS ErrorFlag
FROM @Table ;

運行上面的SQL將返回99。

結果快照如下所示:

結果快照

這是因為errorFlag不是XML文檔的根元素。 您可以指定從根元素到errorFlag完整路徑,例如*:

SELECT @nodeVal =  @xml.value('(/*/*/*/errorFlag)[1]', 'int')

或者,您可以使用后代或自身軸( // )來按名稱獲取元素,而不管其在XML文檔中的位置如何,例如:

SELECT @nodeVal =  @xml.value('(//errorFlag)[1]', 'int')

*: 我使用*代替實際的元素名稱只是為了簡化表達式。 您還可以將實際元素名稱與名稱空間一起使用,如其他答案所示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM