从文档中选择的节点获取XML path

问题描述 投票:0回答:1
为此,我选择了与XPath的节点相匹配的三个节点:

第一个

第二秒
    第三三分
  • 第四次
    //client-agent
  • 如我在代码上方列表中所述,在节点t.n上有一个表达式(例如本机
  • /root/other/client-agent
    /root/other/other/client-agent
  • )以获取列[path-i-want-to-get]上的xpath?
  • 	
    不幸的是,没有简单的方法可以在SQL Server中获得此功能。 您可以使用一些Xquery通过XML中的所有节点下降,检查上下文节点,然后返回节点名称。对于大量节点,这可能非常降低。
  • 如果SQL Server支持
  • /root/other/other/client-agent
    函数,甚至是
    /root/other/other/client-agent/client-agent
  • 轴。
逻辑是:

SET

begin
    declare @Xml xml

    set @Xml = convert(xml,'<root><other><client-agent type="a" /><other><client-agent type="b" /><client-agent type="c" ><some-info /></client-agent></other></other></root>')

    select @Xml

    select t.n.value('@type','varchar(max)') as [client-agent@type]
         , t.n.query('.') OuterXml
         , 'Is there a "t.n.SomeXmlFunction(WithTheRequiredParameters)" expression to get the node path' as [the-path-i-want-to-get]
      from @Xml.nodes('//client-agent') as t(n)
end
到上下文节点。 从XML顶部通过所有后代节点的环。
如果该节点具有任何后代节点(包括本身),以...

sql-server t-sql xpath xquery
1个回答
0
投票
.query()

然后返回
.value('','')
加上该节点的名称。

我们需要使用

path-to-node-with-pos

返回所有这些文本节点,然后将它们全部转换为一个字符串。
  • ancestor::
    这不会返回每个节点的位置。为此,您需要一个更复杂的Xquery,它也无法使用
  • $current
  • 函数。因此,我们需要计算所有以前的匹配节点。
      逻辑是:
      • $current
        循环变量,上升到父母,然后获取所有后代节点...
      ...该节点的名称与
    • /
  • 的名称相同
  • ...并且在文档中比
    .query
  • .value
  • 添加
    select t.n.value('@type','varchar(max)') as [client-agent@type], t.n.query('.') OuterXml, t.n.query(' let $current := . for $i in //* [ descendant-or-self::node() [. is $current ] ] return concat("/", local-name($i)) ').value('text()[1]', 'nvarchar(max)') as [the-path-i-want-to-get] from @Xml.nodes('//client-agent') as t(n);
    .
position(.)

DB<>小提琴
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.