2
votes
DECLARE @XML XML
SET @xml = '
<root>
    <a>
        <DATE_OF_BIRTH> 19871224</DATE_OF_BIRTH> 
        <DRIVER> MIKE </DRIVER> 
    </a>
    <a>
        <DATE_OF_BIRTH> 19881124</DATE_OF_BIRTH> 
        <DRIVER> TOM </DRIVER> 
    </a>
    <a>
        <DATE_OF_BIRTH> 19770601</DATE_OF_BIRTH> 
        <DRIVER> DAVID </DRIVER> 
    </a>
</root>'

select x.value('.','varchar(100)')
from @xml.nodes('//a') as T(X)

I want to use xquery to return the element name

The result like this

DATE_OF_BIRTH

DRIVER

How can I make this happen?

Thank you very much.

2
This is the same answer you are looking for: stackoverflow.com/questions/15680259/parse-xml-in-sql-server - pcbabu

2 Answers

3
votes

If you try the following:

select X.query('local-name(.)')
from @xml.nodes('//a/*') as T(X)

it will return:

DATE_OF_BIRTH
DRIVER
DATE_OF_BIRTH
DRIVER
DATE_OF_BIRTH
DRIVER
3
votes

Use local-name() (or name() if you want to include the namespace), so it should be

//a/*/local-name()