XSLT: Select following-sibling until reaching a specified tag

Try this: (Instead of asking for all the p’s we ask for all the p’s whose most recently preceding h1 is current.)

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

    <xsl:template match="https://stackoverflow.com/">
        <content>
            <xsl:apply-templates/>
        </content>
    </xsl:template>

    <xsl:template match="h1">
        <xsl:variable name="header-id" select="generate-id(.)"/>
        <section>
            <sectionHeading>
                <xsl:apply-templates/>
            </sectionHeading>
            <sectionContent>
                <xsl:for-each select="following-sibling::p[generate-id(preceding-sibling::h1[1]) = $header-id]">
                    <paragraph>
                        <xsl:value-of select="."/>
                    </paragraph>
                </xsl:for-each>
            </sectionContent>
        </section>
    </xsl:template>

    <xsl:template match="p"/>
</xsl:stylesheet>

Leave a Comment