Reputation: 357
I am currently trying to use sum in my XSLT file, and am encountering some issues with the right XPath syntax to use. Hopefully you guys can help.
<all>
<courses>
<allcourses>
<course>
<c_code>U65</c_code>
<c_title>Computer Science</c_title>
<student>
<studentID>10265654</studentID>
<fname>Sarah</fname>
<lname>Clarke</lname>
<results>
<u_title>Communicating in an IT Environment</u_title>
<u_code>CSG1132</u_code>
<u_points>15</u_points>
<result>65</result>
<grade>CR</grade>
</results>
<results>
<u_title>Programming Principles</u_title>
<u_code>CSP1150</u_code>
<u_points>15</u_points>
<result>45</result>
<grade>N</grade>
</results>
</student>
<student>
*same structure again for each student
</student>
I was wondering what would be the best way to calculate the total number of for each INDIVIDUAL student? I have tried using the sum function among other XPath syntax to no avail, any suggestions would be greatly appreciated.
Oh and also this is part of my XSLT:
<xsl:for-each select="all/courses/allcourses/course[c_code=$sid]">
<strong>Course Code: </strong> <xsl:value-of select="c_code" /><hr />
<strong>Course Name: </strong> <xsl:value-of select="c_title" /><br />
<xsl:for-each select="student">
<strong> Student ID: </strong> <xsl:value-of select="studentID" /> <br />
<strong> First Name: </strong> <xsl:value-of select="fname" /> <br />
<strong> Last Name: </strong> <xsl:value-of select="lname" /> <br />
<xsl:for-each select="results">
<strong> Unit Code: </strong> <xsl:value-of select="u_code" /> <br />
<strong> Unit Title: </strong> <xsl:value-of select="u_title" /> <br />
<strong> Unit Result: </strong> <xsl:value-of select="result" /> <br />
<strong> Unit Grade: </strong> <xsl:value-of select="grade" /> <br />
<strong> Unit Points </strong> <xsl:value-of select="sum(grade)" /> <br />
<xsl:variable name="CountPoints" select="sum(/student | //u_points)" />
Upvotes: 0
Views: 2183
Reputation: 437
It is better to avoid for-each. Use apply-templates instead:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:template match="student">
<xsl:apply-templates select="node() except results"/>
total per student: <xsl:value-of select="sum(results/result)"/>
<!--or sum(results/u_points|results/result) -->
</xsl:template>
<xsl:template match="lname|fname|studentID">
<xsl:apply-templates/><xsl:text> </xsl:text>
</xsl:template>
Upvotes: 2
Reputation: 70618
Within the xsl:for-each that iterates over each student (but not within the nested for-each on results, you can get the sum of all result totals like so...
<xsl:value-of select="sum(results/u_points)" />
The xpath expression here is relative to the current student you are positioned on, and will sum up all results within that student element.
Upvotes: 3