Reputation: 2741
The table is called school. it has two columns called students
and teachers
. I want to add teachers and students names to respective column. this is my 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>
this is my xsl file as referenced by xml file
<?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>
but it prints the table like this.
is there anyway to add students and teachers names to their respective column?
Upvotes: 0
Views: 1243
Reputation: 167516
Use
<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>
Upvotes: 2