XML查询和检索节点值

时间:2019-01-20 23:06:49

标签: sql sql-server

我正在尝试从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值。

3 个答案:

答案 0 :(得分:0)

在XPath /cpCollection/group/property[@id='Credit']中返回

<property id="Credit">
  <value>0.25</value>
</property>

因此,以这种方式尝试

F.X.value('[@id="Credit"]', 'Nvarchar(8)')  As Credit 

答案 1 :(得分:0)

ZLK的答案奏效了。 F.X.value('(.[@id="Credit"]/value/text())[1]','nvarchar(8)') As Credit

答案 2 :(得分:0)

ForEach Controller 2

结果:

    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
相关问题