I'm using XSLT for some output formatting, and I want a wrapper element around every N nodes of the output. I've read xslt - adding </tr><tr> every n node?, but my problem is that the source nodes have to come from a lookup:
<xsl:for-each select="key('items-by-product', $productid)">
rather than just a template match. All the examples I've found assume that the nodes you want are all next to each other, and they're just counting siblings.
I have a solution that works for me:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:variable name='num_per_div' select='2' />
<xsl:variable name='productid' select='1' />
<xsl:output method="xml" indent="yes"/>
<xsl:key name="items-by-product" match="item" use="productid"/>
<xsl:template match="data">
<output>
<xsl:for-each select="key('items-by-product', $productid)">
<xsl:variable name='pos' select='position()' />
<xsl:if test="position() = 1 or not((position()-1) mod $num_per_div)">
<outer pos="{$pos}">
<xsl:for-each select="key('items-by-product', $productid)">
<xsl:variable name='ipos' select='position()' />
<xsl:if test="$ipos >= $pos and $ipos < $pos + $num_per_div">
<inner>
<xsl:value-of select="itemid"/>
</inner>
</xsl:if>
</xsl:for-each>
</outer>
</xsl:if>
</xsl:for-each>
</output>
</xsl:template>
</xsl:stylesheet>
with data
<data>
<item>
<productid>1</productid>
<itemid>1</itemid>
</item>
<item>
<productid>1</productid>
<itemid>2</itemid>
</item>
<item>
<productid>2</productid>
<itemid>A</itemid>
</item>
<item>
<productid>1</productid>
<itemid>3</itemid>
</item>
<item>
<productid>2</productid>
<itemid>B</itemid>
</item>
<item>
<productid>1</productid>
<itemid>4</itemid>
</item>
</data>
which produces
<?xml version="1.0" encoding="utf-8"?>
<output>
<outer pos="1">
<inner>1</inner>
<inner>2</inner>
</outer>
<outer pos="3">
<inner>3</inner>
<inner>4</inner>
</outer>
</output>
But this is looping through all the nodes for each node, which strikes me as inefficient.
Is there a better approach that will produce the same output more efficiently? Can the following-sibling techniques work with a filter?