John Sheehan
John Sheehan

Reputation: 78132

Dividing a list of nodes in half

<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?

Upvotes: 4

Views: 2812

Answers (4)

jelovirt
jelovirt

Reputation: 5892

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>

Upvotes: 7

samjudson
samjudson

Reputation: 56873

You could try using the last() function which will give you the size of the current context:

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

Upvotes: 2

codeape
codeape

Reputation: 100816

Try count(../node). The following will gives the correct result on my test XML file (a simple nodes root with node elements), using the xsltproc XSLT processor.

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

Upvotes: 0

A. Rex
A. Rex

Reputation: 32001

I'm not at all sure, but it seems to me that count(*) is not doing what you think it is. That counts the number of children of the current node, not the size of the current node list. Could you print it out to check that it's 8 or 9 instead of 12?

Use last() to get the context size.

Upvotes: 0

Related Questions