使用t-SQL检索XML元素名称

Mat*_*t W 18 xml sql t-sql sql-server xpath

如果我有:

<quotes>
  <quote>
    <name>john</name>
    <content>something or other</content>
  </quote>
  <quote>
    <name>mary</name>
    <content>random stuff</content>
  </quote>
</quotes>
Run Code Online (Sandbox Code Playgroud)

如何使用T-SQL获取元素名称'name'和'content'的列表?

我到目前为止最好的是:

declare @xml xml
set @xml = ...
select r.value('quotes/name()[1]', 'nvarchar(20)' as ElementName
from @xml.nodes('/quotes') as records(r)
Run Code Online (Sandbox Code Playgroud)

但是,当然,我不能让这个工作.

Mat*_*t W 32

实际上,对不起,我得到的最好的是:

select distinct r.value('fn:local-name(.)', 'nvarchar(50)') as t
FROM
    @xml.nodes('//quotes/*/*') AS records(r)
Run Code Online (Sandbox Code Playgroud)

我猜我回答了自己的问题......


小智 6

DECLARE @xml as xml
SET @xml = '<Address><Home>LINE1</Home></Address>'

SELECT Nodes.Name.query('local-name(.)') FROM @xml.nodes('//*') As Nodes(Name)
Run Code Online (Sandbox Code Playgroud)

这将给出所有元素的列表