解析XML属性

时间:2014-04-16 15:19:52

标签: sql xml parsing

以下是我尝试解析的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>

我需要返回文本字符串,例如&#34; 1药物&#34;只有在选择属性的情况下才会选择&#39;是真的。

我有以下选择:

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)

1 个答案:

答案 0 :(得分:0)

你可以用一些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)')