tags:

views:

734

answers:

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

A: 

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.

A. Rex
+6  A: 

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>
jelovirt
+1 for sure .. :-)
infant programmer
A: 

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>
codeape
+1  A: 

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