【问题标题】:Parsing XML Attributes解析 XML 属性
【发布时间】:2014-04-17 03:40:46
【问题描述】:

以下是我尝试解析的 XML 示例:

<question-multichoice id="s2q1" name="">
  <text lang="en">How many medications are you taking?
</text>
  <options>
    <option id="19DEC09B9F" selected="false">
      <text lang="en">0 medications</text>
    </option>
    <option id="899D0E0798" points="1" selected="true">
      <text lang="en">1 medication</text>
    </option>
    <option id="E1315F7EDA" points="2" selected="false">
      <text lang="en">2 medications</text>
    </option>
    <option id="246B1927E8" points="3" selected="false">
      <text lang="en">3+ medications</text>
    </option>
  </options>
</question-multichoice>

我只需要在属性“selected”为真的情况下返回文本字符串,例如“1 drug”。

我有以下选择:

SELECT T3.loc3.value('options[1]', 'varchar(3000)') as response

以下交叉适用:

cross apply qa.XmlData.nodes('//section') as T2(Loc)
cross apply T2.Loc.nodes('./elements/child::*') as T3(loc3)

【问题讨论】:

    标签: sql xml parsing


    【解决方案1】:

    你可以用一些 xpath 来挑选元素:

    declare @xml xml
    set @xml =
    '<question-multichoice id="s2q1" name="">
        <text lang="en">How many medications are you taking?</text>
        <options>
            <option id="19DEC09B9F" selected="false">
                <text lang="en">0 medications</text>
            </option>
            <option id="899D0E0798" points="1" selected="true">
                <text lang="en">1 medication</text>
            </option>
            <option id="E1315F7EDA" points="2" selected="false">
                <text lang="en">2 medications</text>
            </option>
            <option id="246B1927E8" points="3" selected="false">
                <text lang="en">3+ medications</text>
            </option>
        </options>
    </question-multichoice>'
    
    -- get the option element that has the selected attribute set to "true"
    select @xml.value('(/question-multichoice/options/option[@selected="true"]/text)[1]', 'nvarchar(100)')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 2010-11-02
      • 2010-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多