XSLT:如何动态循环并调用模板和显示项目?

时间:2012-01-23 05:57:42

标签: xslt loops

我有这样的XML

<info>list1</info>
<count>24</count>
<rtag>1111</rtag>
<rtag>2222</rtag>   ------upto 24 rtags

我想显示如下内容

list1   1111 2222 3333 ----------upto 10 items{next line}
          1011 1022 1033-----------upto 10 times{next line}
          1001 1002 1003--till remaining items 

在这种情况下,我从后端开始计数。我想通过调用template.can动态使用count值显示上面显示的项目。有人请帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="Windows-1252" />
  <xsl:strip-space elements="*" />

  <xsl:variable name="padding1" select="'        '" /><!-- first col -->
  <xsl:variable name="padding2" select="'      '" />  <!-- remaining cols -->
  <xsl:variable name="per-row"  select="10" />        <!-- column count -->

  <xsl:template match="list">
    <xsl:value-of select="info" />
    <xsl:value-of select="substring($padding1, string-length(info) + 1)" /> 
    <xsl:apply-templates select="rtag" />
  </xsl:template>

  <xsl:template match="rtag">
    <xsl:choose>
      <xsl:when test="position() mod $per-row = 1 and position() &gt; 1">
        <xsl:value-of select="$padding1" />
        <xsl:call-template name="padded-value" />
      </xsl:when>
      <xsl:otherwise>
        <xsl:call-template name="padded-value" />
        <xsl:if test="position() mod $per-row = 0 or position = last()">
          <xsl:value-of select="'&#10;'" />
        </xsl:if>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template name="padded-value">
    <xsl:value-of select="substring($padding2, string-length() + 1)" /> 
    <xsl:value-of select="." />
  </xsl:template>
</xsl:stylesheet>

适用于

<list>
  <info>list1</info>
  <count>24</count>
  <rtag>1111</rtag><rtag>1111</rtag><rtag>1111</rtag><rtag>1111</rtag><rtag>1111</rtag>
  <rtag>1111</rtag><rtag>1111</rtag><rtag>1111</rtag><rtag>1111</rtag><rtag>1111</rtag>
  <rtag>222</rtag><rtag>2222</rtag><rtag>2222</rtag><rtag>2222</rtag><rtag>2222</rtag>
  <rtag>2222</rtag><rtag>2222</rtag><rtag>2222</rtag><rtag>2222</rtag><rtag>2222</rtag>
  <rtag>333</rtag><rtag>3333</rtag><rtag>3333</rtag><rtag>3333</rtag>
</list>

产生

list1     1111  1111  1111  1111  1111  1111  1111  1111  1111  1111
           222  2222  2222  2222  2222  2222  2222  2222  2222  2222
           333  3333  3333  3333