[英]Retrieving an XML node value with TSQL?
What am I not getting here? 我什么不来? I can't get any return except NULL...
除了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
Here is the solution: 解决方法如下:
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 ;
Running the above SQL will return 99. 运行上面的SQL将返回99。
Snapshot of the result is given below, 结果快照如下所示:
That's because errorFlag
is not the root element of your XML document. 这是因为
errorFlag
不是XML文档的根元素。 You can either specify full path from root element to errorFlag
, for example* : 您可以指定从根元素到
errorFlag
完整路径,例如*:
SELECT @nodeVal = @xml.value('(/*/*/*/errorFlag)[1]', 'int')
or you can use descendant-or-self axis ( //
) to get element by name regardless of it's location in the XML document, for example : 或者,您可以使用后代或自身轴(
//
)来按名称获取元素,而不管其在XML文档中的位置如何,例如:
SELECT @nodeVal = @xml.value('(//errorFlag)[1]', 'int')
*: I'm using *
instead of actual element name just to simplify the expression. *: 我使用
*
代替实际的元素名称只是为了简化表达式。 You can also use actual element names along with the namespaces, like demonstrated in the other answer. 您还可以将实际元素名称与名称空间一起使用,如其他答案所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.