RE: [xsl] Simple list -> Nested list based on attribute values

Subject: RE: [xsl] Simple list -> Nested list based on attribute values
From: "Andrew Welch" <ajwelch@xxxxxxxxxxxxxxx>
Date: Fri, 20 Aug 2004 09:37:58 +0100
> I have an XML document of the form
>
> <doc>
>   <item header='true'>Section 1</item>
>   <item>Section 1.1</item>
>   <item>Section 1.2</item>
>
>   <item header='true'>Section 2</item>
>   <item>Section 2.1</item>
>   <item>Section 2.2</item>
> </doc>
>
> that I want to transform to the following:
>
> <doc>
>   <section title="Section 1">
>     <item>Section 1.1</item>
>     <item>Section 1.2</item>
>   </section>
>
>   <section title="Section 2">
>     <item>Section 2.1</item>
>     <item>Section 2.2</item>
>   </section>
> </doc>
>
> I was able to match the @header <item>s with the rule
> 'item[@header = "true"]' but couldn't work out a predicate to
> match "all subsequent <item>s up until the next @header <item>".


An XSLT 2.0 solution (almost an exact copy of one in the spec), that
takes advantage of the new for-each-group and group-starting-with:


<xsl:template match="doc">
    <doc>
        <xsl:for-each-group select="item"
group-starting-with="item[@header]">
            <section title="{current-group()/self::item[@header]}">
                <xsl:for-each
select="current-group()[self::item][not(@header)]">
                    <xsl:copy-of select="."/>
                </xsl:for-each>
            </section>
        </xsl:for-each-group>
    </doc>
</xsl:template>

cheers
andrew

Current Thread