繁体   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