XSLT 1.0和字符串计数

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中,我无法更改变量值。这种无状态、函数评估的方式让我感到困惑。
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>

因为symphony-cms使用XSLT 1.0,如果我有能力的话,我会换掉它。 - Colin Brogan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接