hyp*_*lug 0 xml xslt multiple-columns
我需要这个XML,
<list columns="3">
<item>martin</item>
<item>donald</item>
<item>whistler</item>
<item>mother</item>
<item>carl</item>
<item>liz</item>
<item>cosmo</item>
</list>
Run Code Online (Sandbox Code Playgroud)
看起来像这样:
<table>
<tr>
<td>martin</td>
<td>donald</td>
<td>whistler</td>
</tr>
<tr>
<td>mother</td>
<td>carl</td>
<td>liz</td>
</tr>
<tr>
<td>cosmo</td>
<td></td>
<td></td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
什么时候columns="4",它应该是这样的:
<table>
<tr>
<td>martin</td>
<td>donald</td>
<td>whistler</td>
<td>mother</td>
</tr>
<tr>
<td>carl</td>
<td>liz</td>
<td>cosmo</td>
<td></td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
有关XSLT文件应该是什么样子的任何提示?我可以说,它需要某种循环(递归?),但我不确定是否有更优雅的方式.
我将采用的方法是通过使用每个项目上位置()的"mod"函数来匹配第1,第4,第7位置的项目.
匹配每个这样的项目后,只需根据列数循环遍历以下兄弟.
对于最后一行,可能没有足够的项来完成行,有一个递归模板,可以根据最后一行中有多少项添加到空单元格中.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Global variable to get column count -->
<xsl:variable name="columns" select="number(/list/@columns)"/>
<!-- Match the root node -->
<xsl:template match="list">
<table>
<!-- Match items in the 1st, 4th, 7th positions, etc (or whatever the column variable holds) -->
<xsl:apply-templates select="item[position() mod $columns = 1]"/>
</table>
</xsl:template>
<xsl:template match="item">
<tr>
<!-- Output the current item -->
<td>
<xsl:value-of select="."/>
</td>
<!-- Output the following items based on the number of required columns -->
<xsl:for-each select="following-sibling::item[position() < $columns]">
<td>
<xsl:value-of select="."/>
</td>
</xsl:for-each>
<!-- Add in any empty cells if numberof following items is not sufficient -->
<xsl:call-template name="emptycell">
<xsl:with-param name="cellcounter" select="count(following-sibling::item[position() < $columns]) + 1" />
</xsl:call-template>
</tr>
</xsl:template>
<!-- Recursive template to add in empty cells when there are not enough items to complete a row -->
<xsl:template name="emptycell">
<xsl:param name="cellcounter" />
<xsl:if test="$cellcounter < $columns">
<td></td>
<xsl:call-template name="emptycell">
<xsl:with-param name="cellcounter" select="$cellcounter + 1" />
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5798 次 |
| 最近记录: |