4

所以我试图解决 xslt 中的一个问题,我通常知道如何用命令式语言来解决这个问题。我正在从 xml 元素列表中将单元格添加到表格中,标准的东西。所以:

<some-elements>
  <element>"the"</element>
  <element>"minds"</element>
  <element>"of"</element>
  <element>"Douglas"</element>
  <element>"Hofstadter"</element>
  <element>"and"</element>
  <element>"Luciano"</element>
  <element>"Berio"</element>
</some-elements>

但是,我想在达到某个字符最大值后切断一行并开始新的一行。所以说我最多允许每行 20 个字符。我最终会得到这个:

<table>
 <tr>
  <td>"the"</td>
  <td>"minds"</td>
  <td>"of"</td>
  <td>"Douglas"</td>
 </tr>
 <tr>
  <td>"Hofstadter"</td>
  <td>"and"</td>
  <td>"Luciano"</td>   
 </tr>
 <tr>
  <td>"Berio"</td>
 </tr>
</table>

在命令式语言中,我会将元素附加到一行,同时将每个元素字符串计数添加到某个可变变量。当该变量超过 20 时,我将停止,构建一个新行,然后在将字符串计数归零后重新运行该行上的整个过程(从停止的元素开始)。但是,我无法更改 XSLT 中的变量值。这整个无状态的函数评估事情让我陷入了循环。

4

1 回答 1

9

从xsl-list来到这个论坛就像回到10年前,为什么大家都用xslt 1:-)

<xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output indent="yes"/>

<xsl:template match="some-elements">
 <table>
  <xsl:apply-templates select="element[1]"/>
 </table>
</xsl:template>


<xsl:template match="element">
 <xsl:param name="row"/>
 <xsl:choose>
  <xsl:when test="(string-length($row)+string-length(.))>20
          or
          not(following-sibling::element[1])">
   <tr>
    <xsl:copy-of select="$row"/>
    <xsl:copy-of select="."/>
   </tr>
   <xsl:apply-templates select="following-sibling::element[1]"/>
  </xsl:when>
  <xsl:otherwise>
   <xsl:apply-templates select="following-sibling::element[1]">
    <xsl:with-param name="row">
     <xsl:copy-of select="$row"/>
     <xsl:copy-of select="."/>
    </xsl:with-param>
   </xsl:apply-templates>
  </xsl:otherwise>
 </xsl:choose>
</xsl:template>
</xsl:stylesheet>
于 2012-03-11T10:45:58.083 回答