Reputation: 78132
<xsl:for-each select="./node [position() <= (count(*) div 2)]">
<li>foo</li>
</xsl:for-each>
<xsl:for-each select="./node [count(*) div 2 < 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
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() <= $mid]">
<li>foo</li>
</xsl:for-each>
<xsl:for-each select="$nodes[$mid < position()]">
<li>bar</li>
</xsl:for-each>
Upvotes: 7
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() <= last() div 2]">
<li>foo</li>
</xsl:for-each>
<xsl:for-each select="./node [last() div 2 < position()]">
<li>bar</li>
</xsl:for-each>
Upvotes: 2
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() <= (count(../node) div 2)]">
...
</xsl:for-each>
<xsl:for-each select="node[(count(../node) div 2) < position()]">
...
</xsl:for-each>
Upvotes: 0
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