【问题标题】:How can I group homogenous data in xsl?如何在 xsl 中对同质数据进行分组?
【发布时间】:2012-02-09 07:34:00
【问题描述】:

假设我们有以下数据:

<all>
    <item id="1"/>
    <item id="2"/>
    ...
    <item id="N"/>
</all>

对这些项目进行分组的最优雅的 xslt 方式是什么? 例如,假设我们想要一个每行有两个单元格的表格。 我能想象到我的头顶(虽然没有经过测试) 在模板中,匹配项目,我可以调用这个项目,选择following-sibling。 但即使在这种情况下,我也应该传递额外的参数,以使递归有限。

【问题讨论】:

标签: xslt


【解决方案1】:

由于行数可以是可变的 .. 我将它作为参数传递给模板 .. :)

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes"/>

  <xsl:template match="/all[node]">
    <table>
      <xsl:for-each select="node[1]">
        <xsl:call-template name="whoaa">
          <xsl:with-param name="count" select="'1'"/>
          <xsl:with-param name="row_count" select="'10'"/>
          <!--maximum row_count is set to 10 -->
        </xsl:call-template>
      </xsl:for-each>
    </table>
  </xsl:template>

  <xsl:template name="whoaa">
    <xsl:param name="count"/>
    <xsl:param name="row_count"/>
    <!--check if we have crossed row_count-->
    <xsl:if test="not ($row_count &lt; $count)">
      <tr>
        <td>
          <xsl:value-of select="."/>
        </td>
        <td>
          <!--copy next column-->
          <xsl:for-each select="following-sibling::node[1]">
            <xsl:value-of select="."/>
          </xsl:for-each>
        </td>
      </tr>
      <!--Select next row .. call the same template untill we reach (row_count > count)-->
      <xsl:for-each select="following-sibling::node[2]">
        <xsl:call-template name="whoaa">
          <xsl:with-param name="count" select="$count+2"/>
          <xsl:with-param name="row_count" select="$row_count"/>
        </xsl:call-template>
      </xsl:for-each>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

【讨论】:

  • 假设您的示例 XML 是这样的。如果输入 XML 的结构发生变化,那么其 &lt;template match=""/&gt; 也会发生变化。
【解决方案2】:

使用位置和模式,例如

<xsl:template match="/all">
    <table>
    <xsl:apply-templates name="item" mode="group"/>
    </table>
</xsl:template>

<xsl:template match="item[position() mod 2=1]" mode="group">
<tr>
<td><xsl:apply-templates select="." mode="render"/></td>
<td><xsl:apply-templates select="following-sibling::item[1]" mode="render"/></td>
</tr>
</xsl:template>

<xsl:template match="item[position() mod 2=0]"></xsl:template>

<xsl:template match="item" mode="render">item: <xsl:value-of select="@id"/></xsl:template>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    相关资源
    最近更新 更多