gpt4 book ai didi

sql-server - TSQL XML 值返回所有记录节点的第一个值

转载 作者:数据小太阳 更新时间:2023-10-29 02:56:10 25 4
gpt4 key购买 nike

我想使用 tsql 从 xml 文件中获取 ChargeType 的值。我写了脚本,但它总是为两个 xml 记录返回值“Principal”。我不明白哪里出了问题以及如何解决问题?脚本应返回值:

ChargeType
Principal
Taxed

当前结果

ChargeType
Principal
Principal

源代码

DECLARE @xml XML = '<ListFinancialEventsResponse xmlns="http://www.test.com">
<ListFinancialEventsResult>
<FinancialEvents>
<ShipmentEventList>
<ShipmentEvent>
<ShipmentItemList>
<ShipmentItem>
<ItemChargeList>
<ChargeComponent>
<ChargeType>Principal</ChargeType>
<ChargeAmount>
<CurrencyAmount>20.4</CurrencyAmount>
<CurrencyCode>RUR</CurrencyCode>
</ChargeAmount>
</ChargeComponent>
<ChargeComponent>
<ChargeType>Taxed</ChargeType>
<ChargeAmount>
<CurrencyAmount>1.23</CurrencyAmount>
<CurrencyCode>GEL</CurrencyCode>
</ChargeAmount>
</ChargeComponent>
</ItemChargeList>
</ShipmentItem>
</ShipmentItemList>
</ShipmentEvent>
</ShipmentEventList>
</FinancialEvents>
</ListFinancialEventsResult>
</ListFinancialEventsResponse>';


;WITH XMLNAMESPACES('http://www.test.com' as ns)
select
lfer.c.value('(//ns:ChargeType)[1]', 'nvarchar(50)') AS ChargeType
from @xml.nodes('//ns:ListFinancialEventsResponse//ns:ListFinancialEventsResult//ns:ShipmentItemList//ns:ShipmentItem//ns:ItemChargeList//ns:ChargeComponent') lfer(c)

最佳答案

好吧,要么您需要指定<ChargeType> 以上节点的整个列表在你的 XPath 中,使用破折号(现在,你遗漏了一些)

@xml.nodes('/ns:ListFinancialEventsResponse/ns:ListFinancialEventsResult/ns:FinancialEvents/ns:ShipmentEventList .......

或者您需要使用此 XPath 来获取 <ChargeComponent>节点并获取 <ChargeType>从那些。

试试这个 T-SQL:

;WITH XMLNAMESPACES('http://www.test.com' as ns)
SELECT
-- do *NOT* use double dashes here!
lfer.c.value('(ns:ChargeType)[1]', 'nvarchar(50)') AS ChargeType
FROM
-- just grab *all* <ChargeComponent> nodes anywhere in the XML
@xml.nodes('//ns:ChargeComponent') lfer(c)

您现有的代码:

lfer.c.value('(//ns:ChargeType)[1]'

表示:给我所有 <ChargeType>节点(因为前导 // ),然后获取所有这些节点的 first - 这就是为什么您要使用 Principal 获取节点的原因两次

关于sql-server - TSQL XML 值返回所有记录节点的第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com