xsl - 使用div包装for-each中的每2个项目

时间:2013-08-01 11:12:59

标签: xslt

我有一个xsl:for-each,我想在div中包装每两个项目。怎么做?

<xsl:for-each select="$datapath/PackageInfoList/PackageInfo">

<!-- lots of html in here -->

</xsl:for-each>

结果将是:

<div>
<!-- lots of html in here -->
<!-- lots of html in here -->
</div>
<div>
<!-- lots of html in here -->
<!-- lots of html in here -->
</div>

1 个答案:

答案 0 :(得分:6)

选择奇数<PackageInfo>元素,例如

<xsl:for-each select="$datapath/PackageInfoList/PackageInfo[position() mod 2 = 1]">
  <div>
     <!-- lots of html in here -->

     <!-- do something with following-sibling::PackageInfo[1] -->
  </div>
</xsl:for-each>

这将针对位置1,3,5等处的元素运行。手动处理相应的第一个<PackageInfo>


更惯用的

<xsl:template match="/">
  <xsl:apply-templates select="$datapath/PackageInfoList/PackageInfo" mode="group2" />
</xsl:template>

<xsl:template match="PackageInfo" mode="group2">
  <xsl:if test="position() mod 2 = 1">
    <div>
      <xsl:apply-templates select=". | following-sibling::PackageInfo[1]" />
    </div>
  </xsl:if>
</xsl:template>

<xsl:template match="PackageInfo">
  <!-- lots of html in here -->
</xsl:template>

更灵活

<xsl:template match="/">
  <xsl:apply-templates select="$datapath/PackageInfoList/PackageInfo" mode="group">
    <xsl:with-param name="groupcount" select="2" />
  </xsl:apply-templates>
</xsl:template>

<xsl:template match="PackageInfo" mode="group">
  <xsl:param name="groupcount" select="2" />

  <xsl:if test="position() mod $groupcount = 1">
    <div>
      <xsl:apply-templates select=". | following-sibling::PackageInfo[position() &lt; $groupcount]" />
    </div>
  </xsl:if>
</xsl:template>

<xsl:template match="PackageInfo">
  <!-- lots of html in here -->
</xsl:template>