Dealing with Attributes and Elements in XPath with XSLT using ASP.NET 2.0 - Displaying an HTML table based on the hierarchy
(Page 5 of 6 )
Now, let us proceed to generate an HTML table based on the XML document we have. The following is the first approach (using separate templates) we can use to accomplish the same:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<table border="1">
<tr>
<xsl:apply-templates select ="EmployeeDetails/Department"/>
</tr>
</table>
</xsl:template>
<xsl:template match="EmployeeDetails/Department">
<td colspan="3">
<b>
Department: <xsl:value-of select ="@Dname"/>
</b>
</td>
<xsl:apply-templates select ="Employee"/>
</xsl:template>
<xsl:template match ="Employee" >
<tr>
<td>
<xsl:value-of select ="Empno"/>
</td>
<td>
<xsl:value-of select ="Ename"/>
</td>
<td>
<xsl:value-of select ="Sal"/>
</td>
</tr>
</xsl:template>
</xsl:stylesheet>
The total skill lies in identifying and placing the tags appropriately at their respective positions in the templates. The following is the second approach we can use to accomplish the same task (using a nested “xsl:for-each” construct):
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<table border="1">
<xsl:for-each select="EmployeeDetails/Department">
<tr>
<td colspan="3">
<b>
Department: <xsl:value-of select ="@Dname"/>
</b>
</td>
</tr>
<xsl:for-each select="Employee">
<tr>
<td>
<xsl:value-of select ="Empno"/>
</td>
<td>
<xsl:value-of select ="Ename"/>
</td>
<td>
<xsl:value-of select ="Sal"/>
</td>
</tr>
</xsl:for-each>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
In any of the above cases, when the above XSLT gets executed, the transformation should look something like the following:
<table border="1">
<tr>
<td colspan="3">
<b>Department: Accounting</b>
</td>
</tr>
<tr>
<td>1001</td>
<td>Jagadish</td>
<td>3400</td>
</tr>
<tr>
<td>1002</td>
<td>Chatarji</td>
<td>2500</td>
</tr>
<tr>
<td>1003</td>
<td>Winner</td>
<td>4300</td>
</tr>
.
.
.
</table>
Next: Searching for an element at a particular location >>
More ASP.NET Articles
More By Jagadish Chaterjee