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

如何用XSL 3.0按group属性值将XML文档分组为chapter元素?

XSLT 3.0 Solution to Group Documents by group Attribute

Since your XML is already sorted by the group value, we can use XSLT 3.0's xsl:for-each-group with group-adjacent to efficiently wrap consecutive documents into chapter elements. Here's a complete stylesheet that does exactly what you need:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!-- Identity template: copies all nodes/attributes by default -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <!-- Process the root corpus element -->
  <xsl:template match="corpus">
    <xsl:copy>
      <!-- Group consecutive documents by their front/group/@n value -->
      <xsl:for-each-group select="document" group-adjacent="front/group/@n">
        <!-- Create a chapter element with the group key as its n attribute -->
        <chapter n="{current-grouping-key()}">
          <!-- Apply templates to all documents in the current group -->
          <xsl:apply-templates select="current-group()"/>
        </chapter>
      </xsl:for-each-group>
    </xsl:copy>
  </xsl:template>

  <!-- Exclude the group element from the front section of each document -->
  <xsl:template match="front/group"/>

</xsl:stylesheet>

How This Works:

  1. Identity Template: This is the default template that copies every node and attribute unless another template specifically matches it. It preserves all your existing content except where we explicitly override it.
  2. Corpus Template: We wrap the grouping logic here. Using group-adjacent is ideal because your documents are already sorted by group—this groups consecutive documents with the same group value without needing to re-sort.
  3. Chapter Creation: For each group, we create a <chapter> element with the group's key (the value of front/group/@n) as its n attribute.
  4. Removing the Group Element: The empty template matching front/group ensures that this element is not copied to the output, which matches your desired structure.

This solution is efficient, clean, and leverages XSLT 3.0's grouping capabilities perfectly for your sorted input.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:52:47