Accessing variables outside of for-each in XSLT

2019-09-09 02:52发布

问题:

I am having issues at the moment with the scope of certain variables within my XSLT document, here is the section of code in question:

<xsl:for-each select="all/courses/allcourses/course">
  <a>
    <xsl:attribute name="href">javascript:void(0)</xsl:attribute>
    <xsl:attribute name="onclick">javascript:transform('<xsl:value-of select="c_code"/>');</xsl:attribute>
    <xsl:value-of select="c_title"/>
  </a>
  <br/>
  <br/>
  <course code="{c_code}">
    <strong> Enrolled: </strong>
    <xsl:variable name="courseCreditPoints" select="coursecp"/>
    <xsl:variable name="numberOfEnrolled" select="count(student[sum(results/u_points)!= $courseCreditPoints])"/>
    <xsl:value-of select="$numberOfEnrolled"/>
    <br/>
    <strong> Graduated: </strong>
    <xsl:value-of select="count(student[sum(results/u_points) = $courseCreditPoints])"/>
    <br/>
    <xsl:variable name="numberOfGraduates" select="count(student[sum(results/u_points) = $courseCreditPoints])"/>
  </course>
</xsl:for-each>

<br/>
<strong> Total number of students: </strong>
<xsl:variable name="totalStudents" select="count(//studentID)"/>
<xsl:value-of select="$totalStudents"/>
<strong> Total enrolled students: </strong>

What I am trying to achieve: I am trying to access the variables within the for-each loop outside of it. What I want to be able to do is subtract the $numberOfGraduates variables from the variable $totalStudents (I can access this one, as it is declared outside of the loop) but I cannot do so as $numberOfGraduates is declared within the loop. I have tried just subtracting it within the loop, which works, but then it will print out the result several times.

What is the best way to go about accessing these variables within the for-each loop?

Thanks guys!

回答1:

Your variable numberOfGraduates is per course, it has to be calculated for-each course separately, as you did.

Variable totalStudents is one for all courses. One student can take two courses, be sure that you do not count one student twice:

<xsl:variable name="totalStudents" select="count(distinct-values(//studentID))"/>