如何访问 XML 的值

how to access value of XML

SQL 服务器 2012

如何从 XML 下面访问 "datefrom" 值?几乎尝试了所有方法但没有成功:(

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope">
   <SOAP-ENV:Body>
      <ns0:getInterestAndExchangeRatesResponse xmlns:ns0="http://swea.riksbank.se/xsd">
         <return>
            <datefrom>2020-03-05</datefrom>
            <dateto>2020-03-05</dateto>
         </return>
      </ns0:getInterestAndExchangeRatesResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

您需要尊重正在使用的 XML 命名空间 - 但一旦您这样做了,这应该对您有用:

DECLARE @Data XML = '....(your XML here).....';

-- define the two XML namespaces in play
WITH XMLNAMESPACES('http://www.w3.org/2003/05/soap-envelope' AS soap,
                   'http://swea.riksbank.se/xsd'AS ns)
SELECT
    @Data.value('(soap:Envelope/soap:Body/ns:getInterestAndExchangeRatesResponse/return/datefrom)[1]', 'varchar(20)')

这将 return 类似于:

2020-03-05