Get the average of elements values in xsl

2020-04-26 06:13发布

问题:

I've been dealing with xsl for the first time today. The XML file I have looks like the following:

<student_course>
<students>
    <student num="">
    <name gender=""></name>
    <course cid="1"></course>
    <course cid="2"></course>
    <course cid="3"></course>
    <course cid="4"></course>
    <comments></comments>
    </student>  
</students>
<courses>
    <course cid="1"></course>
    <course cid="2"></course>
    <course cid="3"></course>
    <course cid="4"></course>
</courses>
</student_course>

There are 10+ students, and I need to print out all the grades for each course for each student. That I've done using for-each. What I need to do, is at the bottom of the column, show the average grade for that course (student/course) I was thinking a variable would be the way to go, and increment it in the for-each and divide it or something, but that does not seem to work, everytime I try to make a variable I can only call it immediately after I set it, I must be doing something wrong. How would I get the average for all values under student_courses/students/student/course[@cid]?

Currently I have my xsl display a table with 4 columns and 11 rows (1 row for the titles, and 10 for the student grades) and then a 12th row to have the averages.

Thanks in advanced!

回答1:

I figured it out. To get the average, the easiest way was to use a for-each and the sum() and count() functions. All I needed was to add this where ever I wanted the average to display:

<xsl:value-of select="sum(/student_course/students/student/course[@cid='1']) div count(/student_course/students/student/course[@cid='1'])"/>

and just change the cid value for the different courses.