[英]XML Query and Retrieving Node Value
我正在嘗試從XML獲取節點的值。 這是XML的簡短示例
<cpCollection moduleId="cc5005f4-f1ea-433e-b187-8b769170eae4" dataId="0a0e2ddf-2a38-4739-9a52-000f9698978f">
<group id="Serialize" name="Serialize">
<property id="Headline">
<value>One, Two, Three</value>
</property>
<property id="Credit">
<value>0.25</value>
</property>
</group>
</cpCollection>
我的一些查詢如下:
select TOP 1000 I.Attributes.value('@id', 'nvarchar(32)') as item_name,
F.X.value('@id', 'nvarchar(32)') as field_id,
F.X.value('data(.)', 'nvarchar(256)') as field_value,
F.X.value('Deck[1]','NVarChar(512)') AS Deck,
F.X.value('Credit[1]', 'Nvarchar(8)') As Credit
from cpsys_DataCurrent as T
cross apply T.Attributes.nodes('/cpCollection/group') as I(attributes)
cross apply I.attributes.nodes('property') as F(X)
我沒有獲得“標題”或“信用”的價值。 只是NULL值。
在XPath中, /cpCollection/group/property[@id='Credit']
返回
<property id="Credit">
<value>0.25</value>
</property>
因此,以這種方式嘗試
F.X.value('[@id="Credit"]', 'Nvarchar(8)') As Credit
ZLK的答案奏效了。 FXvalue('(.[@id="Credit"]/value/text())[1]','nvarchar(8)') As Credit
DECLARE @cpsys_DataCurrent TABLE ( xmltext XML);
INSERT INTO @cpsys_DataCurrent (xmltext)
VALUES
( N'<cpCollection moduleId="cc5005f4-f1ea-433e-b187-8b769170eae4" dataId="0a0e2ddf-2a38-4739-9a52-000f9698978f">
<group id="Serialize" name="Serialize">
<property id="Headline">
<value>One, Two, Three</value>
</property>
<property id="Credit">
<value>0.25</value>
</property>
</group>
</cpCollection>');
SELECT TOP 1000
T.xmltext.value('(cpCollection/@dataId)[1]', 'nvarchar(32)') as item_name,
T.xmltext.value('(cpCollection/group/@id)[1]', 'nvarchar(32)') as field_id,
T.xmltext.value('data(cpCollection/group/property)[1]', 'nvarchar(256)') as field_value,
T.xmltext.value('(cpCollection/group/property[@id="Headline"]/value)[1]','NVarChar(512)') AS Deck,
T.xmltext.value('(cpCollection/group/property[@id="Credit"]/value)[1]', 'Nvarchar(8)') As Credit
from @cpsys_DataCurrent as T
結果:
item_name field_id field_value Deck Credit
0a0e2ddf-2a38-4739-9a52-000f9698 Serialize One, Two, Three One, Two, Three 0.25
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.