Reputation: 1118
I have the following xml:
<root>
<elements>
<element>
<data1>Foo</data1>
<data2>Bar</data2>
</element>
<element>
<data1>Foo1</data1>
<data2>Bar1</data2>
</element>
<element>
<data1>Foo2</data1>
<data2>Bar2</data2>
</element>
<element>
<data1>Foo3</data1>
<data2>Bar3</data2>
</element>
</elements>
</root>
I want to get the first half of the list in a structure (html table) and the second in another structure.
I am trying this:
<xsl:template match="root">
<xsl:variable name="set" select="elements/element" />
<xsl:variable name="count" select="count($set)" />
<xsl:for-each select="elements/element" >
<xsl:if test="position() < $count div 2" >
<table>
<xsl:apply-templates select="elements/element" />
</table>
</xsl:if>
<xsl:else>
<table>
<xsl:apply-templates select="elements/element" />
</table>
</xsl:else>
</xsl:for-each>
I have 2 issues: 1. else is not allowed in for-each. 2. Is there a better solution for this besides counting the elements and using foreach?
Upvotes: 0
Views: 190
Reputation: 1118
yes, I realized right after I posted that I could go with
<table>
<xsl:apply-templates select='documents/document[(position()+1) mod 2 = 0]' />
</table>
<table>
<xsl:apply-templates select='documents/document[(position()+1) mod 2 = 1]' />
</table>
Martin's solution should work as well I think. I think it is fair to accept his solution even if mine does not require counting the elements.
NOTE: This solution will not solve the original issue. The first table will not contain the first half of the original xml, but the data on even positions in the original xml. The second table will contain the data on odd position. My original xml is not ordered, so this will work for me.
Upvotes: 0
Reputation: 167706
You can simply use
<xsl:template match="root">
<xsl:variable name="set" select="elements/element" />
<xsl:variable name="count" select="count($set)" />
<table>
<xsl:apply-templates select="$set[position() < $count div 2]" />
</table>
<table>
<xsl:apply-templates select="$set[position() >= $count div 2]" />
</table>
</xsl:template>
Upvotes: 1