简体   繁体   English

如何使用sql从同一级别的所有xml元素中选择属性

[英]How to select an attribute from all xml elements on the same level with sql

My xml is: 我的xml是:

<foo>
    <bar>
        <button text="a"/>
        <button text="b"/>
        <button text="c"/>
    </bar>
</foo>

With the following I'm able to get one of those text values, but I'm trying to get all 3 back (each on their own row). 通过下面的代码,我能够获得这些文本值之一,但是我试图将所有三个值都返回(每个都在自己的行上)。 I realize [1] is why I'm getting one back... but I'm not sure how to get all of them back? 我意识到[1]是为什么要让我回来的原因...但是我不确定如何让他们全部回来?

select 
    cast(f.xml as xml).value('(/foo/bar/button/@text)[1]', 'varchar(max)') as foo
from
    (select top 1 * from files) f

This returns 这返回

Foo
---
 a

Where I'm actually trying to get 我实际上试图去的地方

Foo
---
 a
 b
 c

You need to use the nodes operator in your FROM , which you can do by using a CROSS APPLY : 您需要在FROM使用nodes运算符,您可以通过使用CROSS APPLY来做到这一点:

DECLARE @XML xml = '
<foo>
    <bar>
        <button text="a"/>
        <button text="b"/>
        <button text="c"/>
    </bar>
</foo>';

SELECT fb.button.value('@text','char(1)')
FROM (VALUES(@XML))X(XMLString)
     CROSS APPLY X.XMLSTRING.nodes('foo/bar/button') fb(button);

I think this query does the trick: 我认为此查询可以解决问题:

declare @xml as xml = 
'<foo>
    <bar>
        <button text="a"/>
        <button text="b"/>
        <button text="c"/>
    </bar>
</foo>'

select T.C.value('@text','varchar(50)') as button
FROM @xml.nodes('/foo/bar/button') as T(C)

输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM