如何用XSL汇总节点?

时间:2015-02-22 14:34:13

标签: xml xslt nodes

Hi, I found this,但不是我想要的。我想要这个输出

司机B 27

司机A 18

这是XML:

<grid>
    <driver>
        <name>Driver B</name>
        <points>
            <imola>10</imola>
            <monza>9</monza>
            <silverstone>8</silverstone>
        </points>
    </driver>
    <driver>
        <name>Driver A</name>
        <points>
            <imola>7</imola>
            <monza>6</monza>
            <silverstone>5</silverstone>
        </points>
    </driver>
</grid>

这是XSLT:

 <xsl:template match="/grid">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title>Championship</title>
        </head>
        <body>
            <h1>Classification</h1>
            <xsl:apply-templates select="driver" />
        </body>
    </html>
</xsl:template>
<xsl:template match="driver">
    <xsl:for-each select=".">
        <p>
            <xsl:value-of select="name" />
            <xsl:value-of select="sum(???)" /> <!-- Here, I don't know the code to sum the points of the races-->

    </xsl:for-each>
</xsl:template>

我确信解决方案很简单,但我无法找到它。感谢。

1 个答案:

答案 0 :(得分:2)

你可以这样做:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns="http://www.w3.org/1999/xhtml">
  <xsl:output method="html" indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="/grid">
    <html>
      <head>
        <title>Championship</title>
      </head>
      <body>
        <h1>Classification</h1>
        <xsl:apply-templates select="driver" />
      </body>
    </html>
  </xsl:template>
  <xsl:template match="driver">
    <p>
      <xsl:value-of select="concat(name, ' ', sum(points/*))" />
    </p>
  </xsl:template>
</xsl:stylesheet>

此处,*表示“匹配任何子元素”。

这会产生输出:

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Championship</title>
  </head>
  <body>
    <h1>Classification</h1>
    <p>Driver B 27</p>
    <p>Driver A 18</p>
  </body>
</html>
相关问题