parsing xml using tsql

Hi,

I am trying to parse a snippet of xml using the following tsql. It is working without errors but I am getting null data rather than the values in double quotes:

DECLARE @x XML;

SET @x = '
<logger>
<TH date="20150730133052" id="th0" temp="21.9" hum="61" dew="14.0"/>
<WIND date="20150730133114" id="wind0" dir="0" gust="0.0" wind="0.0" chill="21.9"/>
<RAIN date="20150730133016" id="rain0" rate="0.0" total="0.0" delta="0.0"/>
<THB date="20150730133040" id="thb0" temp="24.0" hum="53" dew="13.8" press="1021.7" seapress="1022.0" fc="2"/>
</logger>';

SELECT tbl.TH.value('date[1]', 'varchar(100)') AS [date]
	,tbl.TH.value('id[1]', 'varchar(100)') AS id
	,tbl.TH.value('temp[1]', 'varchar(100)') AS temp
	,tbl.TH.value('hum[1]', 'varchar(100)') AS hum
	,tbl.TH.value('dew[1]', 'varchar(100)') AS dew
FROM @x.nodes('/logger/TH') AS tbl(TH);

Open in new window


Thank you
crompnkData Management SpecialistAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:
It's cause you want the attributes, not elements below <th>. Thus you need to query them:

SELECT  tbl.TH.value('@date', 'VARCHAR(100)') AS [date] ,
        tbl.TH.value('@id', 'VARCHAR(100)') AS id ,
        tbl.TH.value('@temp', 'FLOAT') AS temp ,
        tbl.TH.value('@hum', 'INT') AS hum ,
        tbl.TH.value('@dew', 'FLOAT') AS dew
FROM    @x.nodes('/logger/TH') AS tbl ( TH );

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.