2009-10-05 171 views
1

我是新來的使用XSLT,並試圖使用Muenchian方法創建數據透視表(因爲它似乎IE仍然不支持XSLT 2.0我認爲我堅持這一點)。我能夠獲得所需的分組,但是我試圖獲得每個組的屬性總和。要完成屬性的總和,我可以使用聚合總和函數,還是必須循環訪問鍵並將值存儲到變量中?這是我到目前爲止有:XSLT樞軸表

<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> 

回答

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> 
+0

這工作,感謝您的幫助! – jwarzech

0

你應該能夠使用金額,如果你可以使用XPath來選擇所需的記錄(一個或多個)的屬性。

不知道你的輸入XML的結構,我不知道這是什麼會,但我想你的情況類似<xsl:value-of select="sum(@cost)"/>

1

由於內環路您當前上下文節點是記錄元素,你需要以確保您的'總和'包含具有匹配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)" /> 
+0

感謝您指出一些我沒有意識到的語法。到目前爲止,只花了幾天時間處理XSLT,所有示例都有幫助! – jwarzech