T-SQL解析XML赋予空白值

时间:2019-04-15 09:04:21

标签: sql sql-server xml tsql xpath

在这里,我已经解决了许多有关此问题的问题,而这些决议似乎都无效。我有以下XML:

DECLARE @XML xml;
SELECT @XML ='<?xml version="1.0" encoding="UTF-8"?>
<hb:MedicalAidMessage xmlns:hb="bridge.co.za/mes" Version="6.0.0">
    <Claim>
        <Details>
            <LineItems>
                <LineItem>
                    <HBBatchNum>2414</HBBatchNum>
                </LineItem>
            </LineItems>
        </Details>
    </Claim>
</hb:MedicalAidMessage>';

和此代码进行解析:

;WITH XMLNAMESPACES ('bridge.co.za/mes' as ns)
SELECT
    ISNULL(T.N.value('HBBatchNum[1]', 'INT'), 0) AS BatchNo
FROM
    @XML.nodes('/Claim/Details/LineItems/LineItem[1]') AS T(N)

这将返回空白值而不是2414。在实时查询中,XML存储在表列中。我只是无法弄清楚为什么我没有得到节点值。

1 个答案:

答案 0 :(得分:4)

很明显……Claim不是根元素。因此,请使用以下之一:

WITH XMLNAMESPACES ('bridge.co.za/mes' AS ns)
SELECT ISNULL(T.N.value('HBBatchNum[1]', 'int'),0) AS BatchNo
FROM @XML.nodes('/ns:MedicalAidMessage/Claim/Details/LineItems/LineItem[1]') AS T(N)

-- WITH XMLNAMESPACES ('bridge.co.za/mes' AS ns)
SELECT ISNULL(T.N.value('HBBatchNum[1]', 'int'),0) AS BatchNo
FROM @XML.nodes('/*:MedicalAidMessage/Claim/Details/LineItems/LineItem[1]') AS T(N)