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

时间:2013-07-25 12:01:05

标签: sql-server xml xml-attribute

我将XML存储到具有不同标记名称但具有相同属性名称的数据库中:

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

这些只是两个例子,但标签名称可以是任何名称。我想从所有节点读取“PropertyName”属性。

有可能吗?如果是,那么请任何人指导我。

2 个答案:

答案 0 :(得分:4)

如果要从所有节点读取PropertyName值,请尝试使用此解决方案:

DECLARE @MyTable TABLE(
    ID INT IDENTITY(1,1) PRIMARY KEY,
    XmlCol XML NOT NULL
);
INSERT  @MyTable(XmlCol)
VALUES  (N'<book Category="Hobbies And Interests" PropertyName="C#" CategoryID="44" />');
INSERT  @MyTable(XmlCol)
VALUES  (N'<sport Category="Hobbies And Interests" PropertyName="Cricket" CategoryID="46" />');
INSERT  @MyTable(XmlCol)
VALUES  (N'<CocoJambo PropertyName="Aircraft carrier" Category="Hobbies And Interests"> <CocoJamboChild PropertyName="Airplane"/> </CocoJambo>');
INSERT  @MyTable(XmlCol)
VALUES  (N'<sport CategoryID="CocoJamboID" />');

SELECT  a.*,
        b.Node.value('(.)','NVARCHAR(100)') AS PropertyName_Value
FROM    @MyTable a
-- OUTER APPLY or CROSS APLLY
OUTER APPLY a.XmlCol.nodes('//@*[local-name(.)="PropertyName"]') b(Node);

结果:

ID          XmlCol                                    PropertyName_Value
----------- ----------------------------------------- ------------------
1           <book Category="Hobbies And Interes ...   C#
2           <sport Category="Hobbies And Intere ...   Cricket
3           <CocoJambo PropertyName="Aircraft c ...   Aircraft carrier
3           <CocoJambo PropertyName="Aircraft c ...   Airplane
4           <sport CategoryID="CocoJamboID" />        NULL

但是如果要显示所有包含至少一个 PropertyName属性的XML框架的行,那么您可以尝试:

SELECT  a.*
FROM    @MyTable a
WHERE   a.XmlCol.exist('//@*[local-name(.)="PropertyName"]')=1;

结果:

ID          XmlCol
----------- ----------------------------------------------------------------------------------
1           <book Category="Hobbies And Interests" PropertyName="C#" CategoryID="44" />
2           <sport Category="Hobbies And Interests" PropertyName="Cricket" CategoryID="46" />
3           <CocoJambo PropertyName="Aircraft carrier" Category="Hobbies And Interests"><CocoJ ...

答案 1 :(得分:3)

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属性的元素,则可以使用:

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

如果您还希望嵌套元素,可以使用:

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