2013-11-25 56 views
0

我有下面的XML,存储在一个表中的一列:如何迭代到每个节点以检索XML中的值?

<Selections> 
<TextSelection> 
<words> 
<index> 0 </index> 
<text> hi </text> 
</words> 
</TextSelection> 
<TextSelection> 
<words> 
<index> 1 </index> 
<text> hello </text> 
</words> 
</TextSelection> 
<id> 1 </id> 
<followtext> yes </followtext> 
<text> hi hello </text> 
<response> greetings </response> 

<TextSelection> 
<words> 
<index> 2 </index> 
<text> dora </text> 
</words> 
</TextSelection> 
<TextSelection> 
<words> 
<index> 3 </index> 
<text> toy</text> 
</words> 
</TextSelection> 
<id> 2 </id> 
<followtext> yes </followtext> 
<text> dora toy </text> 
<response> like dora </response> 
</Selections> 

我需要从上面的XML文本检索和响应。

我用于检索值的查询是:

select xml.value('(/Selections/TextSelection/words/text)[1]', 'varchar(max)') as Selections, xml.value('(/Selections/TextSelection/words/response)[1]', 'varchar(max)') as Response from QResponse where rid = '20'; 

但我返回空值。我如何获得这些价值?还需要迭代下一个后续节点以获取该值?如何做到这一点?

和输出将是:

text   response 
------------------------ 
hi hello  greetings 
dora toy  like dora 

回答

0

你的问题是,你试图让一个兄弟姐妹......但基本上是“跟随我所在的项目”。

和通向:

“的XQuery [值()]:XQuery的语法 '以下同胞' 不支持”。

:<

下面是一个尝试....这会显示错误。

declare @MyData XML 

select @MyData = ' 

<Selections> 
    <id>1</id> 
    <followtext> yes </followtext> 
    <text> hi hello </text> 
    <response> greetings </response> 
    <id>2</id> 
    <followtext> yes </followtext> 
    <text> dora toy </text> 
    <response> like dora </response> 
</Selections> 

' 

    /* 

text   response 
------------------------ 
hi hello  greetings 
dora toy  like dora 
*/ 


SELECT T.c.value('(.)[1]', 'varchar(100)') AS [text] 
, T.c.value('(../response)[1]', 'varchar(100)') AS responseOne 
, T.c.value('../following-sibling::response)', 'varchar(100)') AS responseTwo 

FROM @MyData.nodes('(/Selections/text)') T(c)