在解析元素时获取xml强制转换的Null值" ErrorType"
我将此XML存储在我的SQL数据库列中。
<Response>
<ISSuccessfulPingResponse>false</ISSuccessfulPingResponse>
<PingResponse>
<PriceResult xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://www.test.com/pasd/test.xsd">
<Result>ERROR</Result>
<ErrorType>XML Validation</ErrorType>
<ErrorDescription> equal to 5.</ErrorDescription>
<out>0</out>
</PriceResult>
</PingResponse>
</Response>
我尝试运行一个SQL脚本来获取元素&#34; ErrorType&#34;的值,但是我收到了空值。
SELECT Cast(Result as xml).value ('(/Response/PingResponse/PriceResult/ErrorType)[1]', 'varchar(100)' ) as result from getresults
where Id=23
答案 0 :(得分:2)
由于PriceResult
和所有没有前缀的后代元素(包括ErrorType
)都位于命名空间https://www.test.com/pasd/test.xsd
中,因此您应该可以在此使用WITH XMLNAMESPACES
例如:
;WITH XMLNAMESPACES('https://www.test.com/pasd/test.xsd' as d)
SELECT Cast(Result as xml).value ('
(/Response/PingResponse/d:PriceResult/d:ErrorType)[1]
', 'varchar(100)' ) as result
from getresults where Id=23
基本上,代码定义了使用d
映射到命名空间URI的前缀WITH XMLNAMESPACES
,然后使用它(前缀d
)来引用命名空间中的元素。