简体   繁体   English

如何仅使用xQuery检索属性

[英]How to retrieve attribute only using xQuery

I have a function similiar to the following, returning large chunk of xml (in production environment), In various stages of the application , we need to retrieve only some of the elements or only some attributes from this. 我有一个类似于以下功能的函数,返回大块的xml(在生产环境中),在应用程序的各个阶段,我们只需要从中检索某些元素或某些属性。

create function testrig.fxConfigurations(@context varchar(300)) returns xml as 
begin
return (select 
'<configurations realm="configuration">
    <context name="apera">
        <backends>
            <backend name="Hades">
                <os>HP Unix</os>
                <ip>nnn.nnn.nnn</ip>
                <db vender="Oracle" version="11g">
                    <netconnect>Data Source= (DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = hades)(PORT = 1521)(RECV_BUF_SIZE=1048576))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = baan)));Password=********;User ID=ItsMe;" providerName="Oracle.DataAccess.Client"
                    </netconnect>
                </db>
            </backend>
            <backend name="Athena">
                <os>HP Unix</os>
                <ip>nnn.nnn.nnn</ip>
                <db vender="Oracle" version="11g">
                    <netconnect>Data Source= (DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = hades)(PORT = 1521)(RECV_BUF_SIZE=1048576))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = baan)));Password=********;User ID=ItsMe;" providerName="Oracle.DataAccess.Client"
                    </netconnect>
                </db>
            </backend>
        </backends>
    </context>
</configurations>
')

end 
go

How do I retrieve only the attribute name ie 'Hades','Athena' using xQuery like this 我如何像这样使用xQuery只检索属性名称,即“ Hades”,“ Athena”

select (testrig.fxConfigurations(null).query('configurations/context[@name="apera"]/backends').query('/descendant-or-self::*'))

If you want to concatenate all values of the backend/@name attributes (ala GROUP_CONCAT ): 如果要串联backend/@name属性的所有值(ala GROUP_CONCAT ):

select testrig.fxConfigurations(null)
   .query('data(configurations/context[@name="apera"]/backends/backend/@name)')

If you need to work with the attributes individually, you may need to use nodes to extract them: 如果需要单独使用属性,则可能需要使用nodes来提取它们:

WITH cteXml AS
(
    SELECT testrig.fxConfigurations(null)
           .query('configurations/context[@name="apera"]') as context
)
SELECT Nodes.node.value('@name', 'varchar(50)') AS backEndName
FROM cteXml
    CROSS APPLY cteXml.context.nodes('//backends/backend') as Nodes(node);

Fiddle here 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM