2014-04-16 243 views
0

以下是我試圖解析XML的例子:解析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> 

我需要返回的文本字符串,例如「1個吃藥」只有在「選擇」屬性爲true。

我有以下選擇:

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) 

回答

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)')