【问题标题】:How to iterate to each node to retrieve values in XML?如何迭代每个节点以检索 XML 中的值?
【发布时间】:2013-11-25 08:00:03
【问题描述】:

我有以下 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';

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

输出将是:

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

【问题讨论】:

    标签: sql sql-server xml xpath xmlnode


    【解决方案1】:

    根据对您的 XML 和 select 语句的简要审查,我怀疑您的 XPath 不正确。
    也许试试:

    /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/

    问候,

    【讨论】:

      【解决方案2】:

      你的问题是你试图得到一个兄弟姐妹......但基本上是“跟随我正在做的项目”。

      这导致:

      “XQuery [value()]:不支持 XQuery 语法 'following-sibling'。”

      这是一个尝试......它将显示错误。

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-10
        • 1970-01-01
        • 2014-07-03
        • 1970-01-01
        • 2023-01-03
        相关资源
        最近更新 更多