You need to enable JavaScript to run this app. XSLT如何将连续相邻instructionRow行嵌套到前置item节点中
优惠活动
大模型
产品
解决方案
定价
更多

XSLT如何将连续相邻instructionRow行嵌套到前置item节点中

XSLT 连续instructionRow嵌套至前置itemRow的实现方案

现有逻辑的问题根因

你此前使用的判断表达式test="following-sibling::tr/@class = 'instructionRow'"属于存在性校验:只要当前itemRow节点后方任意位置存在class为instructionRow的tr,就会返回匹配结果,完全没有设置「连续匹配直到遇到非instructionRow节点就停止」的边界规则,因此会出现跨范围匹配的问题。
同时原逻辑对所有tr节点无差别生成平级item节点,和「instructionRow作为子节点嵌套、不独立生成item」的目标不匹配。

纯XSLT实现思路

已知不存在无前置itemRow的孤立instructionRow,因此所有instructionRow必然归属于它前方最近的一个非instructionRow类型的tr节点(即前置itemRow),核心逻辑分为三步:

  • 移除原有针对instructionRow独立生成节点的模板逻辑,直接跳过该类节点的独立输出
  • 仅将class为itemRow的tr作为节点的唯一生成入口
  • 对每个itemRow,精准筛选归属于它的连续instructionRow,生成对应子节点嵌套到内部

核心匹配逻辑说明

实现连续范围筛选的关键是修正instructionRow的归属判断:

对每一个class为instructionRow的tr,查找它前方最近的一个class不是instructionRow的tr,如果该节点就是当前正在处理的itemRow,那么这个instructionRow就属于当前itemRow的连续后置节点范围。
这种匹配方式天然实现了边界截断:只要连续的instructionRow序列中插入了其他类型的tr(比如下一个itemRow),后续的instructionRow的前置最近非instructionRow节点就会切换为新的节点,不会被错误归属到前面的itemRow。
为了兼容纯XSLT 1.0环境,可以通过generate-id()函数比对两个节点是否为同一节点,不需要依赖XSLT 2.0的节点相等判断语法。

可直接复用的代码示例

基础实现(适合中小规模表格)

<!-- 匹配itemRow生成item节点 -->
<xsl:template match="tr[@class='itemRow']">
  <item>
    <!-- 此处保留你原有的提取itemRow自身内容的逻辑,比如读取单元格文本、属性等 -->

    <!-- 筛选当前itemRow后方所有连续归属的instructionRow -->
    <xsl:for-each select="following-sibling::tr[
      @class='instructionRow'
      and
      generate-id(preceding-sibling::tr[not(@class='instructionRow')][1]) = generate-id(current())
    ]">
      <instruction>
        <!-- 此处搬运你原有的处理instructionRow内容的逻辑,比如提取对应单元格文本 -->
        <xsl:copy-of select=".//node()"/>
      </instruction>
    </xsl:for-each>
  </item>
</xsl:template>

<!-- 跳过instructionRow的独立输出,避免生成冗余的平级item -->
<xsl:template match="tr[@class='instructionRow']"/>

优化实现(适合大规模表格,提升处理效率)

如果表格包含数百行以上的节点,频繁遍历兄弟节点会带来性能损耗,可以通过XSLT的key机制预先建立索引,减少重复遍历:

<!-- 预先建立索引:将每个instructionRow关联到它所属的前置非instructionRow的节点ID -->
<xsl:key name="instructionIndex" match="tr[@class='instructionRow']" use="generate-id(preceding-sibling::tr[not(@class='instructionRow')][1])"/>

<xsl:template match="tr[@class='itemRow']">
  <item>
    <!-- 此处保留原有的itemRow内容提取逻辑 -->

    <!-- 直接通过索引取出当前itemRow关联的所有instructionRow,无需重复遍历兄弟节点 -->
    <xsl:for-each select="key('instructionIndex', generate-id(current()))">
      <instruction>
        <!-- 此处保留原有的instructionRow内容提取逻辑 -->
      </instruction>
    </xsl:for-each>
  </item>
</xsl:template>

<xsl:template match="tr[@class='instructionRow']"/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 06:24:07