使用T-SQL解析/查询XML

3

我很久以来一直在解决这个问题,似乎已经接近成功了,但还差一点点就能够达成目标。我的数据库中有一个列,看起来像这样:

<document>
<items>
<item name="one">one is the first number</item>
<item name="two">two is the second number</item>
</items>
</document>

在这个例子中,我需要查询并返回“two是第二个数字”。我也想在不创建临时表的情况下做到这一点。目前我的代码如下:
create table #test (item1 xml)
insert into #test (item1) 
values ('<document> <items> <item name="one">one is the first number</item> <item name="two">two is the second number</item> </items> </document>')

select item1.value('(/document/items/item)[2]', 'nvarchar(max)') from #test
select item1.query('/document/items/item[@name="two"]') from #test

第一个select返回了正确的值,但我需要知道它是第二个“index”。第二个select返回了我想要的内容,但它返回了整个节点two。我错过了什么?是否有一种简单的方法可以使用XML而不需要转换为临时表?
2个回答

6

我也希望能不创建临时表来实现这个目标。

您可以使用数据类型为 XML 的变量。

declare @xml xml

set @xml = 
'<document>
  <items>
    <item name="one">one is the first number</item>
    <item name="two">two is the second number</item>
  </items>
</document>'

select @xml.value('(/document/items/item[@name="two"])[1]', 'nvarchar(max)')

或者您可以在查询中将字符串转换为XML。

select cast(
            '<document>
              <items>
                <item name="one">one is the first number</item>
                <item name="two">two is the second number</item>
              </items>
            </document>' as xml
           ).value('(/document/items/item[@name="two"])[1]', 'nvarchar(max)')

您的第一个查询使用了正确的.value()方法,而您的第二个查询中使用了正确的XQuery表达式。在使用.value()方法时,需要使用返回单个值的XQuery表达式。这将给您所有符合条件的项目节点,例如/document/items/item[@name="two"],其中@name为“two”。在表达式末尾添加[1]可以确保您只获取XML中@name为“two”的第一个出现位置。请注意,HTML标签已被保留,不需要进行解释。

0

首先,你可以使用xml类型的变量,而不是临时表。如下所示,这样的变量可以直接从字符串文字中分配。

因此我认为你想要nametwoitem节点的文本值,这种情况下,你只需要在value()调用中使用适当的xpath条件即可:

DECLARE @x xml

SET @x = '<document> <items> <item name="one">one is the first number</item> 
     <item name="two">two is the second number</item> </items> </document>'

SELECT @x.value('(/document/items/item[@name="two"])[1]', 'nvarchar(max)')

提供

--------------------------------------------------------------
two is the second number

(1 row(s) affected)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接