代码之家  ›  专栏  ›  技术社区  ›  Matteo

属性中具有相同值的XSLT 1.0 count元素,并将其显示

  •  0
  • Matteo  · 技术社区  · 16 年前

    我有一个变量包含:

    <col p1="Newman" p2="Paul"/>
    ...
    <col p1="Newman" p2="Paolo"/>
    <col p1="Newman" p2="Paul"/>
    

    我在输出一个表时,第一列的值是p2,第二列是它出现的时间。对于p2的每个值,我应该只有一行。

    <table>
    <tr><td>p2</td><td>num</td></tr>
    <tr><td>Pault</td><td>2</td>
    ...
    <tr><td>Paolo</td><td>1</td>
    </table>
    
    1 回复  |  直到 9 年前
        1
  •  0
  •   Tomalak    16 年前

    使用XSL键很容易。

    <!-- index all <col> elements by their @p2 attribute -->
    <xsl:key name="kColByFirstname" match="col" use="@p2" />
    
    <xsl:template match="/RootElement">
      <table>
        <tr>
          <td>p2</td><td>num</td>
        </tr>
        <!-- select the respective first <col> of each group -->
        <xsl:apply-templates select="col[
          generate-id() = generate-id(key('kColByFirstname', @p2)[1])
        ]" />
      </table>
    </xsl:template>
    
    <xsl:template match="col">
      <tr>
        <!-- output the current value of @p2 and its group count -->
        <td><xsl:value-of select="@p2"/></td>
        <td><xsl:value-of select="count(key('kColByFirstname', @p2))" /></td>
      </tr>
    </xsl:template>