在解析元素

时间:2016-02-09 08:21:18

标签: sql-server xml xpath

在解析元素时获取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

1 个答案:

答案 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)来引用命名空间中的元素。