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

如何使用XSLT 3.0将Record-Type 6与后续多个Record-Type 4分组?

使用XSLT 3.0合并分组Record-Type 6及其后续Record-Type 4记录

需要将XML输入中的Record-Type 6(行首字符为6的记录)作为主记录,合并其后续所有连续的Record-Type 4(行首字符为4的记录)作为子记录,每个Record-Type 6可对应多个Record-Type 4。

输入XML

<root>
    <row>
        <line>60010010000015</line>
    </row>
    <row>
        <line>40010016009108</line>
    </row>
    <row>
        <line>60010020001556</line>
    </row>
    <row>
        <line>40010026009404</line>
    </row>
    <row>
        <line>40010036009405</line>
    </row>
    <row>
        <line>40010036009406</line>
    </row>
</root>

预期输出XML

<root>
   <row>
      <MainRecord>60010010000015</MainRecord>
      <Record4>
        <SubRecord>40010016009108</SubRecord>
      </Record4>
   </row>
   <row>
      <MainRecord>60010020001556</MainRecord>
      <Record4>
        <SubRecord>40010026009404</SubRecord>
        <SubRecord>40010036009405</SubRecord>
        <SubRecord>40010036009406</SubRecord>
      </Record4>
   </row>
</root>

XSLT 3.0解决方案

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="root">
        <root>
            <!-- 以Record-Type 6的行作为分组起点 -->
            <xsl:for-each-group select="row" group-starting-with="row[starts-with(line, '6')]">
                <row>
                    <!-- 输出主记录 -->
                    <MainRecord>
                        <xsl:value-of select="current-group()[1]/line"/>
                    </MainRecord>
                    <!-- 输出所有对应的Record-Type 4子记录 -->
                    <Record4>
                        <xsl:for-each select="current-group()[position() > 1]">
                            <SubRecord>
                                <xsl:value-of select="line"/>
                            </SubRecord>
                        </xsl:for-each>
                    </Record4>
                </row>
            </xsl:for-each-group>
        </root>
    </xsl:template>
</xsl:stylesheet>

代码说明

  • 使用xsl:for-each-group的group-starting-with属性,指定以行首为6的row元素作为分组起始点,自动将后续连续的行归为同一组,直到遇到下一个行首为6的row。
  • current-group()[1]获取每组第一个元素(Record-Type 6主记录),输出为<MainRecord>。
  • current-group()[position() > 1]获取每组中除第一个元素外的所有元素(对应Record-Type 4子记录),循环输出为<SubRecord>并包裹在<Record4>中。
  • xsl:output设置输出XML时启用缩进,保证格式整洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:09:30