2014-04-16 195 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)')