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.

1
  • 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: stackoverflow.com/questions/2266132/… Commented Apr 14, 2019 at 10:02

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

FYI, the solution came from stumbling across this post: stackoverflow.com/questions/2266132/…
Your answer is fine. You may also want to review this column for some useful XML gymnastics: beyondrelational.com/blogs/jacob/archive/2010/05/30/…
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.