Zyplexx
Zyplexx

Reputation: 19

How to use xslt to calculate average and display results in a table

I am taking an xml class. I am a beginner and I am trying to learn xslt 1.0.

I am trying to figure out how I can calculate the average per student and make the result show in a table for the right student. For now, the average calculation is incorrect and I don't know how I can get the average to show in another column beside the name. Please keep your answer simple as I am a beginner. Thank you !

The result should look like this :

Student        Average
Jeff Cooper     70.0
Laureen Hanley  95.0
Peter Manning   74.3
Robert Shaw     78.7

This is my xml file :

<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet href="temptransfo.xsl" type="text/xsl" ?>
<university>
<student><name>Robert Shaw</name>
<course code="INF4830" note="90" />
<course code="INF1130" note="70" />
<course code="INF1330" note="76" /></student>
<student><name>Peter Manning</name>
<course code="INF4830" note="76" />
<course code="INF1130" note="73" />
<course code="INF1330" note="74" /></student>
<student><name>Jeff Cooper</name>
<course code="INF4930" note="40" />
<course code="INF1130" note="90" />
<course code="INF1330" note="80" /></student>
<student><name>Laureen Hanley</name>
<course code="INF4830" note="92" />
<course code="INF1330" note="98" /></student>
</university>

And this is so far what I've done in my xsl file :

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output 
    method="html"
    encoding="UTF-8"
    doctype-public="-//W3C//DTD HTML 4.01//EN"
    doctype-system="http://www.w3.org/TR/html4/strict.dtd"
    indent="yes" ></xsl:output>

<xsl:template match="/">
<html>
    <head>
    <title>Exercice 1</title>
</head>
<body>

    <table border ="1">
    <caption>Exercice 1</caption>
    <tr>
    <th>Student</th>
    <th>Average</th>
    </tr>
    <xsl:apply-templates select="university/student" >
    <xsl:sort select="substring-after(name,' ')" order="ascending"/>
    </xsl:apply-templates>

    </table>

</body>
</html>         
</xsl:template>

    <xsl:template match="student"> 
    <tr>
    <td>
    <xsl:value-of select="name" />
    </td>
    <td>
    <xsl:value-of select="format-number((sum(preceding::course/@note) div count (preceding::course)),'##.0')"/> 
    </td>
    </tr>
    </xsl:template>

</xsl:stylesheet>

Upvotes: 0

Views: 1396

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117165

IMHO, you have confused yourself by working with an improperly indented XML input. Otherwise you would have seen that course is a child of student, and the average can be computed simply as:

<xsl:value-of select="format-number(sum(course/@note) div count(course),'#.0')"/>

Upvotes: 2

Related Questions