You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在三层嵌套xsl:for-each-group中无需声明变量即可访问父组的current-grouping-key()

如何在嵌套xsl:for-each-group中无需变量访问父组的current-grouping-key()?

当然有更优雅的解决办法!你之前通过声明变量传递父组分键的方式虽然可行,但其实完全可以利用XSLT自带的current-group()函数来简化实现,既不用额外定义变量,还能让代码更简洁高效。

问题根源分析

你原来的代码里,每一层分组都重新用完整的XPath查询整个//results/result节点集,然后手动用父组的键值过滤——这不仅冗余,还需要额外变量来传递上层的分组键。而current-group()函数正好能解决这个问题:它会返回当前xsl:for-each-group处理的分组节点集合,天然继承了父组的筛选范围。

对比实现代码

原实现(依赖变量传递父组键)

<xsl:for-each-group select="//results/result[measuring_plane != '']" group-by="inspection_feature">
  <xsl:variable name="v_current_inspection_feature" select="inspection_feature" as="xs:string"/>
  <xsl:for-each-group select="//results/result[inspection_feature = current-grouping-key() and measuring_plane != '']" group-by="description">
    <xsl:for-each-group select="//results/result[inspection_feature = $v_current_inspection_feature and description = current-grouping-key() and measuring_plane != '']" group-by="step">
      <!-- 你的内层处理逻辑 -->
    </xsl:for-each-group>
  </xsl:for-each-group>
</xsl:for-each-group>

优化后实现(无需变量,用current-group())

<xsl:for-each-group select="//results/result[measuring_plane != '']" group-by="inspection_feature">
  <xsl:for-each-group select="current-group()" group-by="description">
    <xsl:for-each-group select="current-group()" group-by="step">
      <!-- 你的内层处理逻辑 -->
    </xsl:for-each-group>
  </xsl:for-each-group>
</xsl:for-each-group>

为什么这样可行?

  • 最外层分组后,current-group()就是当前inspection_feature对应的所有符合measuring_plane != ''条件的节点,把它作为第二层分组的select参数,就自动限定了范围,不需要再手动过滤inspection_feature。
  • 第二层分组后,current-group()又变成了当前description对应的、属于上层inspection_feature分组的节点子集,传给第三层后,自然包含了两层父组的筛选条件,完全不用再引用父组的键值。

这种方式除了代码更简洁,还能提升性能——因为你不再重复遍历整个results节点集,而是基于父组已经筛选好的子集进行分组,减少了不必要的节点查询操作。

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 01:39:06