3

How can i get the title in the following xml document

DECLARE @xVar XML
SET @xVar = 
  '<reportdata genre="security" publicationdate="2002" ISBN="0-7356-1588-2">
   <title>Writing Secure Code</title>
   <author>
      <first-name>Michael</first-name>
      <last-name>Howard</last-name>
   </author>
   <author>
      <first-name>David</first-name>
      <last-name>LeBlanc</last-name>
   </author>
   <price>39.99</price>
   </reportdata>'

SELECT [Title]= reportdata.item.value('@title', 'varchar(40)')

FROM   @xVar.nodes('/reportdata') AS reportdata(item)

This query always returns null , any ideas?

0

2 Answers 2

3

title is an element not an attribute. The following works.

SELECT [Title]= reportdata.item.value('.', 'varchar(40)')
FROM   @xVar.nodes('/reportdata/title[1]') AS reportdata(item)  
Sign up to request clarification or add additional context in comments.

Comments

2

There is no need to shred the XML in the FROM clause if you only want one value.

SELECT [Title]= @xVar.value('(/reportdata/title)[1]', 'varchar(40)')

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.