0

我在创建 xslt 文件时遇到了这个小问题......我有这个通用 xml 文件:

<data>
  <folder>
    <file>
      <name>file1</name>
      <date>2000</date>
      <index1>1</index1>
      <index2>1</index2>
    </file>

    <file>
      <name>file2</name>
      <date>2001</date>
      <index1>1</index1>
      <index2>1</index2>
    </file>

    <file>
      <name>file3</name>
      <date>2004</date>
      <index1>2</index1>
      <index2>1</index2>
    </file>
  </folder>
</data>

鉴于这个抽象的例子,我必须把它转换成类似的东西:

<table>
  <tr>
    <td>Name</td>
    <td>Date</td>
  </tr>
  <tr>
    <td>file1</td>
    <td>2000</td>
  </tr>
  <tr>
    <td>file2</td>
    <td>2001</td>
  </tr>
</table>

<table>
  <tr>
    <td>Name</td>
    <td>Date</td>
  </tr>
  <tr>
    <td>file3</td>
    <td>2004</td>
  </tr>
</table>

我必须根据 index1 和 index2 对每个表的文件元素进行分组(如 ID 对)。我能够为每个单独的文件创建一个表,但我无法提供为每个文件共享 index1 和 index2 创建一个表的解决方案。有什么想法或建议吗?

4

1 回答 1

0

由于您使用的是 XSLT 2.0,因此您可以使用该xsl:for-each-group语句。您在这里有两个选择,这取决于您是否希望将组保持在一起并尊重顺序,或者您是否只想分组而不考虑顺序。

也就是说,aabaab如果你想要一组(aaaa, bb)or (aa, b, aa, b)

这首先将所有文件元素分组为相同index1index2与文档中的顺序无关(我放入body元素只是为了使其格式正确)

<xsl:template match="folder">
    <body>
    <xsl:for-each-group select="file" group-by="concat(index1, '-', index2)">
        <!-- xsl:for-each-group sets the first element in the group as the context node -->
        <xsl:apply-templates select="."/>
    </xsl:for-each-group>
    </body>
</xsl:template>

<xsl:template match="file">
    <table>
        <tr>
            <td>Name</td>
            <td>Date</td>
        </tr>
        <xsl:apply-templates select="current-group()" mode="to-row"/>
    </table>
</xsl:template>

<xsl:template match="file" mode="to-row">
    <tr>
        <xsl:apply-templates select="name|date"/>
    </tr>
</xsl:template>

<xsl:template match="name|date">
    <td><xsl:apply-templates/></td>
</xsl:template>

第二个版本只需要将第一个模板更改为:

<xsl:template match="folder">
    <body>
    <xsl:for-each-group select="file" group-adjacent="concat(index1, '-', index2)">
        <xsl:apply-templates select="."/>
    </xsl:for-each-group>
    </body>
</xsl:template>
于 2013-10-24T20:00:16.730 回答