我有以下xml代码:
<section>
<text>
<list>
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
<item>Item 4</item>
<item>Item 5</item>
<item>Item 6</item>
<item>Item 7</item>
</list>
</text>
</section>
我正试图找到一种输出方式,如:
<table>
<tr>
<td>Item 1</td>
<td>Item 2</td>
<td>Item 3</td>
</tr>
<tr>
<td>Item 4</td>
<td>Item 5</td>
<td>Item 6</td>
</tr>
<tr>
<td>Item 7</td>
</tr>
</table>
感谢您的帮助
答案 0 :(得分:0)
在Xslt中执行循环的方法是使用递归。可能会有一个较短的答案,但这有效:
<xsl:template match="/">
<xsl:call-template name="helper"/>
<xsl:template>
<xsl:template name="helper">
<xsl:param name="columns" select="3"/>
<!-- do not pass, used for recursion -->
<xsl:param name="current-index" select="1"/>
<xsl:choose>
<xsl:when test="not(/section/text/list/item[position()=$current-index])"/>
<xsl:otherwise>
<tr>
<xsl:call-template name="helper-row">
<xsl:with-param name="columns" select="$columns"/>
<xsl:with-param name="current-index" select="$current-index"/>
<xsl:with-param name="current-column" select="1"/>
</xsl:call-template>
</tr>
<xsl:call-template name="helper">
<xsl:with-param name="columns" select="$columns"/>
<xsl:with-param name="current-index" select="$current-index + $columns"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="helper-row">
<xsl:param name="columns"/>
<xsl:param name="current-index"/>
<xsl:param name="current-column"/>
<xsl:choose>
<xsl:when test="not(/section/text/list/item[position()=$current-index])"/>
<xsl:when test="$current-column <= $columns">
<td>
<xsl:value-of select="/section/text/list/item[position()=$current-index]/text()"/>
</td>
<xsl:call-template name="helper-row">
<xsl:with-param name="columns" select="$columns"/>
<xsl:with-param name="current-index" select="$current-index + 1"/>
<xsl:with-param name="current-column" select="$current-column + 1"/>
</xsl:call-template>
</xsl:when>
</xsl:choose>
</xsl:template>
答案 1 :(得分:0)
在以下样式表中,您需要相应地更新参数'limit':
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs">
<xsl:output method="xml" indent="yes"/>
<xsl:param name="limit" select="'3'"/>
<xsl:template match="/">
<xsl:variable name="list" select="//item"/>
<table>
<xsl:for-each select="1 to xs:integer(((count(//item) - (count(//item) mod xs:integer($limit))) div xs:integer($limit)) +
(if((count(//item) mod xs:integer($limit)) = 0) then 0 else 1))">
<xsl:variable name="lower-limit" select="(position() - 1) * xs:integer($limit)"/>
<xsl:variable name="upper-limit" select="position() * xs:integer($limit)"/>
<tr>
<xsl:for-each select="$list">
<xsl:if test="(position() gt xs:integer($lower-limit)) and (position() le xs:integer($upper-limit))">
<td><xsl:value-of select="."/></td>
</xsl:if>
</xsl:for-each>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>