2015-06-15 103 views
0

我不在这里?我不能让NULL除外任何的回报......使用TSQL检索XML节点值?

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 

回答

0

这里是解决方案:

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

快照下面给出,

Snapshot of the result

+0

谢谢Vimalan。仍然在XPath曲线的陡峭部分。 – dbrosier

0

这是因为errorFlag是而不是XML文档的根元素。您可以指定从根元素完整路径errorFlag,例如*:

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

,或者你可以按名称,无论使用后代或本身轴(//),以获得元素的它的XML文档中的位置,例如:

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

*:我使用*,而不是实际的元素名称只是为了简化的表达。您也可以使用实际的元素名称以及命名空间,如其他答案中所示。