如何用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:
- 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.
- Corpus Template: We wrap the grouping logic here. Using
group-adjacentis ideal because your documents are already sorted by group—this groups consecutive documents with the samegroupvalue without needing to re-sort. - Chapter Creation: For each group, we create a
<chapter>element with the group's key (the value offront/group/@n) as itsnattribute. - Removing the Group Element: The empty template matching
front/groupensures 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
相关产品推荐
相关产品推荐

