RE: [xsl] Transforming an XML document where the content isn't in a special tag

Subject: RE: [xsl] Transforming an XML document where the content isn't in a special tag
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Wed, 17 Aug 2005 08:02:45 +0100
This is actually quite a tricky problem: if you want to read up on it,
search for "positional grouping". You are trying to group a sequence of
adjacent sibling nodes into a single <p> element. The thing that these nodes
have in common is that they are not <header> elements.

There must be a wrapper element in your XML for it to be well-formed, let's
suppose it is:

First Section
This section deals with a lot of <a href="bla.htm">things</a>.
One of them, is...

Second Section
Now, this section is different, becase...

In XSLT 2.0 you can do positional grouping using group-adjacent:

<xsl:template match="doc">
  <xsl:for-each-group select="node()"
    <xsl:when test="self::header">
     <xsl:apply-templates select="current-group()"/>
     <p><xsl:apply-templates select="current-group()"/>

In XSLT 1.0 my preferred approach is what I call "sibling recursion":

<xsl:template match="doc">
  <xsl:for-each select="header">
    <h1><xsl:value-of select="."/></h1>
    <p><xsl:apply-templates select="following-sibling::node()[1]"

<xsl:template match="node()" mode="across">
  <xsl:copy-of select="."/>
  <xsl:apply-templates select="following-sibling::node()[1]" mode="across"/>

<xsl:template match="header" mode="across">
  <!-- do nothing: terminate the recursion -->

>  I can, of course, add a
> </p> before a header and a <p> after it,

No, you can't do that. XSLT creates nodes, not tags. You create a P element
node on a tree, the serializer later turns that into a balanced pair of
tags, <P> and </P>

Michael Kay

Current Thread