首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何迭代到每个节点以检索XML中的值?

如何迭代到每个节点以检索XML中的值?
EN

Stack Overflow用户
提问于 2013-11-25 16:00:03
回答 2查看 81关注 0票数 0

我有以下XML,存储在一个表的一列中:

代码语言:javascript
复制
<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检索文本和响应。

我对检索值的查询是:

代码语言:javascript
复制
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';

但它返回的值为空值。如何获取这些值?我还需要迭代下一个后续节点来获得该值吗?如何做到这一点呢?

输出结果为:

代码语言:javascript
复制
text          response
------------------------
hi hello      greetings
dora toy      like dora
EN

回答 2

Stack Overflow用户

发布于 2013-11-25 19:55:54

根据对XML和select语句的简要回顾,我怀疑您的XPath是不正确的。

也许你可以试试:

代码语言:javascript
复制
/Selections/TextSelection[1]/words[1]/text[1]
/Selections/response[1]

此外,以下链接可能会有所帮助:

http://blog.sqlauthority.com/2010/06/23/sqlauthority-news-guest-post-select-from-xml-jacob-sebastian/

致以敬意,

票数 1
EN

Stack Overflow用户

发布于 2013-11-26 06:45:28

你的问题是,你试图获得一个sibling.......but基本上是“关注我所在的项目”。

这就导致了:

“跟随值():不支持‘XQuery -XQuery’语法。”

:<

这是一个将显示错误的attempt....that。

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20187349

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档