2013-11-20 44 views
2

我試圖找到一種方法來計算父節點中相同節點的總和。XSL如何計算相同的節點名稱?

我有這樣的XML代碼:

<course> 
    <user name="Jack"> 
    <ExerciceNote note="50" /> 
    <Information>The second exercice</Information> 
    <ExerciceNote note="90" /> 
    </user> 
    <user name="Peter"> 
    <ExerciceNote note="60" /> 
    <ExerciceNote note="80" /> 
    <Information>The last exercice</Information> 
    <ExerciceNote note="75" /> 
    </user> 
</course> 

我想calcultate每個Exercice的總和:

<xsl:template match="course"> 
    <html> 
    <body> 
     <p>Student name: <xsl:apply-templates select="user" /> 
     <xsl:value-of select="@name" /> </p> 
    </body> 
    </html> 
</xsl:template> 

<xsl:template match="user"> 
    <xsl:value-of select="@name" /> 
    <xsl:apply-templates select="ExerciceNote" /> 
</xsl:template> 

<xsl:template match="ExerciceNote"> 
    <xsl:value-of select="sum(???)" /> 
</xsl:template> 

我嘗試了很多東西來代替???

我想這樣的結果:

Jack 
total = 140 
Peter 
total = 215 

回答

2

您不必遍歷ExerciceNotes,你可以留在「用戶級別」得到你想要的數據。或者說,sum()希望您指定一組包含數字內容的元素,例如當前選定用戶的子項ExerciceNotes的屬性值@note而不是單個值。

試試這個XSLT樣式表:

<?xml version="1.0" encoding="utf-8"?> 

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

    <xsl:template match="/"> 
    <xsl:text disable-output-escaping='yes'>&lt;!DOCTYPE html></xsl:text> 
    <html> 
    <body> 
     <xsl:apply-templates/> 
    </body> 
    </html> 
    </xsl:template> 

    <xsl:template match="user"> 
    <p><xsl:text>Student name: </xsl:text> 
     <xsl:value-of select="@name"/> 
    </p> 
    <p><xsl:text>total = </xsl:text> 
     <xsl:value-of select="sum(ExerciceNote/@note)"/> 
    </p> 
    </xsl:template> 

</xsl:stylesheet> 
+0

由於採取了幫助,我理解,我只需要留在節點上,並獲得總和!,太棒了! – baronming

0

每個用戶的另一種簡單的模板

一)迭代,然後計算總和

XML PlayGround

<xsl:template match="*"> 
    <table> 
    <xsl:for-each select="/course/user"> 
     <tr> 

      <td> 
       <xsl:value-of select="@name" /> 
      </td> 

     </tr> 
     <tr> 
      <td> 
       Total = 
       <xsl:value-of select="sum(./ExerciceNote/@note)" /> 
      </td> 
     </tr> 
    </xsl:for-each> 
    </table> 
</xsl:template> 
相關問題