Reputation: 97
The below xslt is the template which is getting it's data from sql db. (I am using java spring architecture to pass values to the xslt). There can be n number of values that can be fetched from db(max 500). studentid and subject are the 2 values that are being pulled from DB. Following is a sample of data
Student id | Subject
3111 | 101
3112 | 100
3113 | 110
3114 | 001
subject field contains a 3 digit value, that signifies the subjects Physics, Chemistry and Maths undertaken by the student. 110 means student is enrolled for Physics and Chemistry only. I need to calculate a sum total of the 3 subjects like how many students took physics and how many took chemistry and how many took maths respectively.
I started trying for Physics first and has not succeeded yet. Following is the xslt that I have created using position() to calculate sum. But the output of sum displays as following for Physics (let's say there were 6 students who enrolled for Physics) Physics count: 123456
xslt
<?xml version="1.0" encoding="UTF-8"/>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:csl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="newLine" select="' '"/>
<xsl:text>
Student IDs:
</xsl:text>
<xsl:apply-templates select="//studentid"/>
<xsl:text>
Physics students:
</xsl:text>
<xsl:apply-templates select="//subjects"/>
<xsl:template match="studentid>
<xsl:value-of select="concat(.,$newLine)"/>
</xsl:template>
<xsl:template match="subjects">
<xsl:choose>
<xsl:when test=".='100'">
<xsl:value-of select="position()"/>
</xsl:when>
<xsl:when test=".='110'">
<xsl:value-of select="position()"/>
</xsl:when>
<xsl:when test=".='111'">
<xsl:value-of select="position()"/>
</xsl:when>
<xsl:when test=".='101'">
<xsl:value-of select="position()"/>
</xsl:when>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
Sample Input of studentid:
110
110
101
111
100
Current output:
Physics students: 12345
Expected output:
Physics students: 5
(I will apply the solution for physics students to chemistry and maths subjects). Thanks in advance!
Upvotes: 0
Views: 115
Reputation: 167506
That sounds more like a grouping problem where you can count the members of each group:
<xsl:for-each-group select="student" group-by="subject">
<xsl:value-of select="current-grouping-key(), count(current-group())" separator=": "/>
</xsl:for-each-group>
You haven't shown the XML input structure so the select="student"
and group-by="subject"
are a guess, you will need to adapt them probably.
Upvotes: 1