问题
I have a RSS feed i need to display in a table (its clothes from a webshop system). The images in the RSS vary in width and height and I want to make a table that shows them all. First off i would be happy just to show all of the items in 3 columns, but further down the road i need to be able to specify through a parameter the amount of columns in my table. I run into a problem showing the tr tag, and making it right, this is my Code so far:
<xsl:template match="item">
<xsl:choose>
<xsl:when test="position() mod 3 = 0 or position()=1">
<tr>
<td>
<xsl:value-of select="title"/>
</td>
</tr>
</xsl:when>
<xsl:otherwise>
<td>
<xsl:value-of select="title"/>
</td>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
In RSS all "item" tags are on the same level in the xml, and thus far i need only the title shows. Thr problem seems to be that i need to specify the start tag as well as the end tag of the tr element, and cant get all 3 elements into it, anyone know how to do this?
回答1:
Easy when you step back a bit. Split the problem into smaller parts.
<xsl:param name="numColumns" select="3" />
<xsl:template match="channel">
<table>
<!-- all items that start a column have position() mod x = 1 -->
<xsl:apply-templates
select="item[position() mod $numColumns = 1]"
mode="tr"
/>
</table>
</xsl:template>
<xsl:template match="item" mode="tr">
<tr>
<!-- all items make a column: this one (.) and the following x - 1 -->
<xsl:apply-templates
select=".|following-sibling::item[position() < $numColumns]"
mode="td"
/>
</tr>
</xsl:template>
<xsl:template match="item" mode="td">
<td>
<!-- calculate optional colspan for the last td -->
<xsl:if test="position() = last() and position() < $numColumns">
<xsl:attribute name="colspan">
<xsl:value-of select="$numColumns - position() + 1" />
</xsl:attribute>
</xsl:if>
<xsl:value-of select="title"/>
</td>
</xsl:template>
来源:https://stackoverflow.com/questions/2676956/xslt-creating-a-table-with-varying-amount-of-columns