Question

I have XML stored into database with the different tag names but the same attribute names:

<book Category="Hobbies And Interests" PropertyName="C#" CategoryID="44" />
<sport Category="Hobbies And Interests" PropertyName="Cricket" CategoryID="46" />

These are just two examples but the tag name can be anything. I want to read "PropertyName" attribute from all node.

Is it possible? If yes then please anyone guide me.

Was it helpful?

Solution

declare @xml xml

set @xml = '<book Category="Hobbies And Interests" PropertyName="C#" CategoryID="44" />
<sport Category="Hobbies And Interests" PropertyName="Cricket" CategoryID="46" />'

select T.c.value('@PropertyName', 'varchar(100)')
from @xml.nodes('/*') T(c)

If you expect that there can be elements without PropertyName attribute, you can use:

select T.c.value('@PropertyName', 'varchar(100)')
from @xml.nodes('/*[@PropertyName]') T(c)

If you also expect that elements can be nested, you can use:

select T.c.value('@PropertyName', 'varchar(100)')
from @xml.nodes('//*[@PropertyName]') T(c)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top