这张桌子叫做学校。它有两列名为students
和teachers
。我想在各栏目中添加教师和学生姓名。这是我的xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="school.xsl"?>
<school>
<students>
<student>
<name>Lakshman</name>
</student>
<student>
<name>Tharindu</name>
</student>
</students>
<teachers>
<teacher>
<name>Sarath</name>
</teacher>
<teacher>
<name>Hemantha</name>
</teacher>
<teacher>
<name>Upali</name>
</teacher>
</teachers>
</school>
这是xml文件引用的xsl文件
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>School</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Students</th>
<th>Teachers</th>
</tr>
<td>
<xsl:for-each select="school/students/student">
<tr><td><xsl:value-of select="name"/></td></tr>
</xsl:for-each>
</td>
<td>
<xsl:for-each select="school/teachers/teacher">
<tr><td><xsl:value-of select="name"/></td></tr>
</xsl:for-each>
</td>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
但它会像这样打印表格。
无论如何都要将学生和教师的名字添加到他们各自的栏目中?
答案 0 :(得分:1)
使用
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="students" select="school/students/student"/>
<xsl:variable name="teachers" select="school/teachers/teacher"/>
<xsl:template match="/">
<html>
<body>
<h2>School</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Students</th>
<th>Teachers</th>
</tr>
<xsl:apply-templates select="$students"/>
<xsl:variable name="stud-count" select="count($students)"/>
<xsl:apply-templates select="$teachers[position() > $stud-count]"/>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="student">
<xsl:variable name="pos" select="position()"/>
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="$teachers[$pos]/name"/></td>
</tr>
</xsl:template>
<xsl:template match="teacher">
<tr>
<td> </td>
<td>
<xsl:value-of select="name"/>
</td>
</tr>
</xsl:template>
</xsl:stylesheet>