Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing a list of nodes in half

Tags:

xml

xslt

<xsl:for-each select="./node [position() &lt;= (count(*) div 2)]">
    <li>foo</li>
</xsl:for-each>
<xsl:for-each select="./node [count(*) div 2 &lt; position()]">
    <li>bar</li>
</xsl:for-each>

My list has 12 nodes, but the second list is always 8 and the first is always 4. What's wrong with my selects?

like image 641
John Sheehan Avatar asked Jan 24 '23 03:01

John Sheehan


1 Answers

When you do count(*), the current node is the node element being processed. You want either count(current()/node) or last() (preferable), or just calculate the midpoint to a variable for better performance and clearer code:

<xsl:variable name="nodes" select="node"/>
<xsl:variable name="mid" select="count($nodes) div 2"/>
<xsl:for-each select="$nodes[position() &lt;= $mid]">
  <li>foo</li>
</xsl:for-each>
<xsl:for-each select="$nodes[$mid &lt; position()]">
  <li>bar</li>
</xsl:for-each>
like image 169
jelovirt Avatar answered Jan 31 '23 09:01

jelovirt