Re: [xsl] Grouping with siblings

Subject: Re: [xsl] Grouping with siblings
From: "Graydon graydon@xxxxxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>
Date: Sat, 15 Feb 2025 20:07:34 -0000
On Sat, Feb 15, 2025 at 07:49:50PM -0000, rick@xxxxxxxxxxxxxx scripsit:
> I have a flat file structure and am trying to add structure to it. Here is
> my XML:
[snip]

>     <xsl:template match="div">
>         <book>
>             <xsl:for-each-group
> select="*[starts-with(@sID,'chapter')]|text()"

You want everything, not just the chapters, and likely in the context of
div, so select="*" ought to do it.

> group-starting-with="chapter[@sID]">
>                 <xsl:if test="self::chapter[@sID]">
>                     <chapter number="{@n}">
>                         <title>{@sID}</title>
>                         <xsl:apply-templates select="." mode="group"/>
>                     </chapter>
>                 </xsl:if>
>             </xsl:for-each-group>

Ritual caution: xsl:iterate has the loop nature. xsl:for-each has the
"change the context and for each such context, do this; logically, this all happens at the same time" nature.

I'm honestly not sure what the context item is inside for-each-group; I
am pretty sure you want to be looking at the sequence required by
current-group() rather than the context item.

<xsl:choose>
    <xsl:when test="head(current-group()) instance of element(chapter)">
        <chapter number="{head(current-group())/@number}">
           <title>{head(current-group())/@sID}</title>
           <xsl:apply-templates select="tail(current-group())" />
         </chapter>
    </xsl:when>
    <xsl:otherwise>
        <!-- there could in principle be something ahead of the first
        group; also, maybe we didn't get the test quite right -->
        <xsl:apply-templates select="current-group()" />
    </xsl:otherwise>
</xsl:choose>

(I just typed this, so it might have some syntax glitches.)

Once this works, you're probably going to want to add a test for
"nothing but a chapter in this group" and drop those before you get to
the "nest the content" xsl:when.


--  
Graydon Saunders  | graydonish@xxxxxxxxxxxx
\xDE\xE6s ofer\xE9ode, \xF0isses sw\xE1 m\xE6g.
-- Deor  ("That passed, so may this.")

Current Thread