1

我是使用 XSLT 的新手,并且正在尝试使用 Muenchian 方法创建数据透视表(因为 IE 似乎仍然不支持 XSLT 2.0,我想我对此感到困惑)。我能够获得所需的分组,但是我试图获得每个组的属性总和。要对属性求和,我可以使用聚合求和函数还是必须遍历键并将值存储到变量中?这是我到目前为止所拥有的:

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

<xsl:key name="Person" match="Record" use="@PersonID" />
<xsl:template match="/">
  <html>
  <body>
    <h2>Costs Per Person</h2>
    <table border = "1">
        <thead>
        <tr>
           <th>ID</th>
           <th>Cost</th>
        </tr>
        </thead>
        <tbody>
        <xsl:for-each select="Records/Record[generate-id() = 
         generate-id(key('Person', @PersonID)[1])]">
        <tr>
            <td>
                <xsl:value-of select="@PersonID" />
            </td>

            <td>
                <!-- Sum Of Cost -->
            </td>
        </tr>   
       </xsl:for-each>  
       </tbody>
    </table>
  </body>
  </html>
</xsl:template>
4

3 回答 3

1

因为循环内的当前上下文节点是一个 Record 元素,所以您需要确保您的“总和”包括具有匹配 PersonID 属性的所有记录。这样的事情应该做:

<xsl:value-of select="sum(../Record[@PersonID=current()/@PersonID]/@Cost)" />

或者,因为您知道当前 Record 元素是第一个具有特定 PersonID 属性的元素,所以在这种情况下您也可以这样做

<xsl:value-of select="number(@Cost) + sum(following-sibling::Record[@PersonID=current()/@PersonID]/@Cost)" />
于 2009-10-06T07:41:35.013 回答
1

容易 - 你已经在那里了。请参阅下面的完整解决方案。

另一方面,我建议不要使用<xsl:for-each>赞成<xsl:apply-templates>. 代码变得有点长,但可读性和代码结构有所改善,恕我直言。

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

  <xsl:key name="Person" match="Record" use="@PersonID" />

  <xsl:template match="/">
    <html>
      <body>
        <h2>Costs Per Person</h2>
        <table border = "1">
          <thead>
            <tr>
               <th>ID</th>
               <th>Cost</th>
            </tr>
          </thead>
          <tbody>
            <xsl:apply-templates select="Records/Record" />
          </tbody>
        </table>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="Records/Record">
    <xsl:variable name="thisGroup" select"key('Person', @PersonID)" />

    <xsl:if test="generate-id() = generate-id($thisGroup[1])">
      <tr>
        <td>
          <xsl:value-of select="@PersonID" />
        </td>
        <td>
          <!-- Sum Of Cost -->
          <xsl:value-of select="sum($thisGroup/@Cost)" />
        </td>
      </tr>   
    </xsl:if>  
  </xsl:template>
</xsl:stylesheet>
于 2009-10-06T09:23:13.717 回答
0

如果您可以使用 xpath 来选择所需记录的属性,则应该可以使用 sum。

在不知道您的输入 xml 的结构的情况下,我不知道这会是什么,但我猜您的情况类似于<xsl:value-of select="sum(@cost)"/>

于 2009-10-05T23:01:06.757 回答