I. This XSLT 1.0 transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/*">
<root>
<xsl:apply-templates/>
</root>
</xsl:template>
<xsl:template match="foo[position() mod 5 = 1]">
<branch>
<xsl:copy-of select=
". | following-sibling::*[not(position() > 4)]"/>
</branch>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
when applied on the provided XML document (corrected to well-formed):
<root>
<branch>
<foo>bar</foo>
<foo>bar2</foo>
<foo>bar3</foo>
<foo>bar4</foo>
<foo>bar5</foo>
<foo>bar6</foo>
<foo>bar7</foo>
</branch>
</root>
produces the wanted, correct result:
<root>
<branch>
<foo>bar</foo>
<foo>bar2</foo>
<foo>bar3</foo>
<foo>bar4</foo>
<foo>bar5</foo>
</branch>
<branch>
<foo>bar6</foo>
<foo>bar7</foo>
</branch>
</root>
Explanation:
This is a case of "positional grouping", where every starting element of a group is the first of a 5-tuple (so its position satisfies: position() mod 5 = 1.
II. XSLT 2.0 Solution:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*">
<root>
<xsl:for-each-group select="*/*"
group-adjacent="(position() -1) idiv 5">
<branch>
<xsl:sequence select="current-group()"/>
</branch>
</xsl:for-each-group>
</root>
</xsl:template>
</xsl:stylesheet>
when this XSLT 2.0 transformation is applied on the same XML document (above), the same wanted, correct result is produced.
Explanation:
Proper use of the <xsl:for-each-group> XSLT 2.0 instruction with the group-adjacent attribute and the current-group() function.