且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在不使用SQL Server查询中的节点名称的情况下读取XML节点属性

更新时间:2021-11-08 21:51:55

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)

如果您希望某些元素没有PropertyName属性,则可以使用:

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)