Lavanya
Lavanya

Reputation: 37

Count the number of elements which match a certain criteria using XSLT

I need to count the number of students who have failed an exam or those with some wrong data. This if loop condition is working properly, but the count of the number of students is wrong.

<xsl:if test ="$StudentFinalmark &gt; 100 or $StudentFinalmark &lt; 49">
    <xsl:value-of select = "count(StudentFinalmark)"/>            
</xsl:if>

For example, if there are four failed students and students with two wrong dates, it's coming as 111111

Please help me with the solution.

Upvotes: 0

Views: 3215

Answers (1)

GHC
GHC

Reputation: 2668

Assuming that your xml looked like this (as per your comment below):

<Students>
    <StudentResults>
        <Marks>
            <StudentAssign1>40</StudentAssign1>
            <StudentAssign2>40</StudentAssign2>
            <StudentExam>40</StudentExam>
        </Marks>
    </StudentResults>
    <StudentResults>
        <Marks>
            <StudentAssign1>1</StudentAssign1>
            <StudentAssign2>2</StudentAssign2>
            <StudentExam>3</StudentExam>
        </Marks>
    </StudentResults>
    <StudentResults>
        <Marks>
            <StudentAssign1>33</StudentAssign1>
            <StudentAssign2>33</StudentAssign2>
            <StudentExam>33</StudentExam>
        </Marks>
    </StudentResults>
</Students>

an XSLT like this will return the results you are after:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <xsl:element name="Output">
            <xsl:value-of select="count(Students/StudentResults[sum(Marks/*) &gt; 100 or sum(Marks/*) &lt; 49])" />
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

This returns the result:

<Output>2</Output>

It returns two because, in the example XML above, the first StudentResults has a sum of 120 (which fails because it is bigger than 100) and the second has a sum of 6 (which fails because it is less than 49)

The trick is to output a single item which is a count of the elements which you select via xpath, not via an "if" and "for" combination. There isn't a need to use a variable either.

Upvotes: 3

Related Questions