试图了解xsl:密钥

问题描述:

我是新来的xslt,我正在尝试学习xslt 1.0。试图了解xsl:密钥

我想弄清楚如何我可以用我的XML文件获得以下结果。我用xsl文件打了很多东西,但是我觉得有些东西我根本得不到,因为它根本不起作用...

请保持您的回答简单,因为我是初学者。谢谢 !

结果应该是这样的:

Code  Number of students Average per course 
INF4830  3     86.0 
INF1130  3     77.7 
INF1330  4     82.0 
INF4930  1     40.0 

这是我的xml文件:

<?xml version="1.0" encoding="UTF-8" ?> 
<?xml-stylesheet href="temptransfo.xsl" type="text/xsl" ?> 
<university> 
<student><name>Robert Shaw</name> 
<course code="INF4830" note="90" /> 
<course code="INF1130" note="70" /> 
<course code="INF1330" note="76" /></student> 
<student><name>Peter Manning</name> 
<course code="INF4830" note="76" /> 
<course code="INF1130" note="73" /> 
<course code="INF1330" note="74" /></student> 
<student><name>Jeff Cooper</name> 
<course code="INF4930" note="40" /> 
<course code="INF1130" note="90" /> 
<course code="INF1330" note="80" /></student> 
<student><name>Laureen Hanley</name> 
<course code="INF4830" note="92" /> 
<course code="INF1330" note="98" /></student> 
</university> 

到目前为止,这是我的XSL文件,但它不工作。没有结果显示在表格中...

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output 
    method="html" 
    encoding="UTF-8" 
    doctype-public="-//W3C//DTD HTML 4.01//EN" 
    doctype-system="http://www.w3.org/TR/html4/strict.dtd" 
    indent="yes" ></xsl:output> 

<xsl:key name="mytable" match="student", use="course" /> 
<xsl:template match="/"> 
<html> 
<head> 
<title>Test1</title> 
</head> 
<body> 
<table border="1"> 
<caption>Test1</caption> 
<tr> 
<th>Code</th> 
<th>Number of student</th> 
<th>Course average</th> 
</tr> 
<xsl:for-each select = "//course" > 
<xsl:if test="generate-id(.)=generate-id(key('mytable',course[@code])[1])"> 
<tr> 
<td> <xsl:value-of select="@code"/> </td> 
<td> <xsl:value-of select="count(//course[@code=current()/@code])"/> </td> 
<td> <xsl:value-of select="(sum (//course/@note)) div (count(//course[@code]))"/> </td> 
</tr> 
</xsl:if> 
</xsl:for-each> 
</table> 
</body> 
</html> 
</xsl:template> 
</xsl:stylesheet> 
+0

除了从我在回答中指出的概念性错误中,您也会遇到语法错误:属性之间不能有逗号(在XSLT的第10行中)。 –

首先,您想获得不同课程的列表;对于这一点,你需要让你的钥匙:

<xsl:key name="course-by-code" match="course" use="@code" /> 

接下来,你要重新使用密钥,以获得在每门课程的所有入学名单 - 是这样的:

<xsl:for-each select="/university/student/course[generate-id(.)=generate-id(key('course-by-code', @code)[1])]" > 
    <xsl:variable name="enrollments" select="key('course-by-code', @code)"/> 
    <tr> 
     <td> 
      <xsl:value-of select="@code"/> 
     </td> 
     <td> 
      <xsl:value-of select="count($enrollments)"/> 
     </td> 
     <td> 
      <xsl:value-of select="sum($enrollments/@note) div count($enrollments)"/> 
     </td> 
    </tr> 
</xsl:for-each> 
+0

非常感谢您的帮助。我现在对如何使用xsl:key有了更好的理解。在我的脑海中,它比这更复杂,但你的解释让我更容易理解。非常感谢 ! :-)我是xslt的新手,容易感到困惑,我觉得这并不容易理解。 – Zyplexx