在XPath中使用SUM函数

时间:2014-05-26 18:46:56

标签: xml xslt xpath

我目前正在尝试在我的XSLT文件中使用sum,并且遇到了使用正确的XPath语法的一些问题。希望你们能帮忙。

<all>
    <courses>
    <allcourses>
    <course> 
        <c_code>U65</c_code>
        <c_title>Computer Science</c_title>
        <student>
            <studentID>10265654</studentID>
            <fname>Sarah</fname>
            <lname>Clarke</lname>
            <results>
                    <u_title>Communicating in an IT Environment</u_title>
                    <u_code>CSG1132</u_code>
                    <u_points>15</u_points>
                    <result>65</result>
                    <grade>CR</grade>
            </results>
            <results>
                    <u_title>Programming Principles</u_title>
                    <u_code>CSP1150</u_code>
                    <u_points>15</u_points>
                    <result>45</result>
                    <grade>N</grade>
            </results>
        </student>
        <student>
            *same structure again for each student
        </student>

我想知道计算每个INDIVIDUAL学生总数的最佳方法是什么?我尝试在其他XPath语法中使用sum函数无济于事,我们将非常感谢任何建议。

哦,这也是我的XSLT的一部分:

<xsl:for-each select="all/courses/allcourses/course[c_code=$sid]">
    <strong>Course Code: </strong> <xsl:value-of select="c_code" /><hr />
    <strong>Course Name: </strong> <xsl:value-of select="c_title" /><br />
    <xsl:for-each select="student">
        <strong> Student ID: </strong> <xsl:value-of select="studentID" /> <br />
        <strong> First Name: </strong> <xsl:value-of select="fname" /> <br />
        <strong> Last Name: </strong> <xsl:value-of select="lname" /> <br />

        <xsl:for-each select="results">
            <strong> Unit Code: </strong> <xsl:value-of select="u_code" /> <br />
            <strong> Unit Title: </strong> <xsl:value-of select="u_title" /> <br />
            <strong> Unit Result: </strong> <xsl:value-of select="result" /> <br />
            <strong> Unit Grade: </strong> <xsl:value-of select="grade" /> <br />
            <strong> Unit Points </strong> <xsl:value-of select="sum(grade)" /> <br />
            <xsl:variable name="CountPoints" select="sum(/student | //u_points)" />

2 个答案:

答案 0 :(得分:3)

xsl:for-each 内迭代每个学生(但不在嵌入式 for-each 结果中,你可以得到所有结果总和的总和......

<xsl:value-of select="sum(results/u_points)" />

此处的xpath表达式与您所在的当前学生相关,并将总结该学生元素中的所有结果。

答案 1 :(得分:2)

最好避免每个人。请改用apply-templates:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

版本=&#34; 2.0&#34;&GT;

<xsl:template match="student">
<xsl:apply-templates select="node() except results"/>
total per student: <xsl:value-of select="sum(results/result)"/>
<!--or sum(results/u_points|results/result) -->
</xsl:template>
<xsl:template match="lname|fname|studentID">
<xsl:apply-templates/><xsl:text> </xsl:text>
</xsl:template>

相关问题