简体   繁体   English

XML查询和检索节点值

[英]XML Query and Retrieving Node Value

I'm trying to get the value of the node from XML. 我正在尝试从XML获取节点的值。 Here is a short sample of the 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>

Some of my query is below: 我的一些查询如下:

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)

I am not getting the value for Headline or Credit. 我没有获得“标题”或“信用”的价值。 Just NULL values. 只是NULL值。

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

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

Hence, try it in this way 因此,以这种方式尝试

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

ZLK's answer worked. 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

Result: 结果:

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM