20

If I have:

<quotes>
  <quote>
    <name>john</name>
    <content>something or other</content>
  </quote>
  <quote>
    <name>mary</name>
    <content>random stuff</content>
  </quote>
</quotes>

How do I get a list of the element names 'name' and 'content' using T-SQL?

The best I've got so far is:

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

But, of course, I can't get this to work.

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Matt W
  • 11,753
  • 25
  • 118
  • 215
  • The current answers here do not take into account Element Names that Repeat in a different Context (have a different XML Path, thus a different meaning). You may want to also check out these answers here that include the Path: https://stackoverflow.com/questions/2266132/how-can-i-get-a-list-of-element-names-from-an-xml-value-in-sql-server – MikeTeeVee Apr 14 '19 at 10:02

2 Answers2

36

Actually, sorry, the best I've got is:

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

Guess I answered my own question...

Matt W
  • 11,753
  • 25
  • 118
  • 215
  • 1
    FYI, the solution came from stumbling across this post: http://stackoverflow.com/questions/2266132/how-can-i-get-a-list-of-element-names-from-an-xml-value-in-sql-server – Matt W Jul 05 '10 at 16:10
  • Your answer is fine. You may also want to review this column for some useful XML gymnastics: http://beyondrelational.com/blogs/jacob/archive/2010/05/30/select-from-xml.aspx – Cade Roux Jul 05 '10 at 19:26
6
DECLARE @xml as xml
SET @xml = '<Address><Home>LINE1</Home></Address>'

SELECT Nodes.Name.query('local-name(.)') FROM @xml.nodes('//*') As Nodes(Name)

This will give the list of all elements

Christian Specht
  • 35,843
  • 15
  • 128
  • 182