2013-11-25 100 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)