XML to HTML Transformation with XSLT: A Simple Tutorial
Learn how to transform XML data into HTML using XSLT. This tutorial provides a basic example demonstrating the process of creating an XML file, an XSLT stylesheet, and linking them to generate dynamic HTML output from your XML data.
Transforming XML to HTML with XSLT: A Basic Example
Creating an XML File
First, create a sample XML file. This file (`employee.xml`) contains data about employees. Each employee is represented as an `Employee` element with nested elements for `FirstName`, `LastName`, `NickName`, and `Salary`.
employee.xml
<?xml version="1.0" encoding="UTF-8"?>
<Employees>
<Employee id="1">
<FirstName>Aryan</FirstName>
<LastName>Gupta</LastName>
<NickName>Raju</NickName>
<Salary>30000</Salary>
</Employee>
<Employee id="2">
<FirstName>Sara</FirstName>
<LastName>Khan</LastName>
<NickName>Zoya</NickName>
<Salary>25000</Salary>
</Employee>
<Employee id="3">
<FirstName>Peter</FirstName>
<LastName>Symon</LastName>
<NickName>John</NickName>
<Salary>10000</Salary>
</Employee>
</Employees>
Creating an XSLT Stylesheet
Next, create an XSLT stylesheet file. This file (`employee.xsl`) defines the rules for transforming the XML data into HTML. This stylesheet specifies that the output should be an HTML table with specific column headers.
employee.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>
<head><title>Employees</title></head>
<body>
<table border="1">
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Salary</th>
</tr>
<xsl:for-each select="/Employees/Employee">
<tr>
<td><xsl:value-of select="@id"/></td>
<td><xsl:value-of select="FirstName"/></td>
<td><xsl:value-of select="LastName"/></td>
<td><xsl:value-of select="NickName"/></td>
<td><xsl:value-of select="Salary"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Linking the Stylesheet to the XML
Finally, link the XSLT stylesheet to the XML file using the `xml-stylesheet` processing instruction within the XML declaration. This tells the XML processor which stylesheet to use to transform the XML data.
Updated employee.xml
<?xml version="1.0" encoding="UTF-8"
standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="employee.xsl"?>
<Employees>
<Employee id="1">
<FirstName>Aryan</FirstName>
<LastName>Gupta</LastName>
<NickName>Raju</NickName>
<Salary>30000</Salary>
</Employee>
<!-- ... more employees ... -->
</Employees>
When you open this XML file in a browser (like Internet Explorer), the browser will apply the XSLT transformation and render the HTML table.
Conclusion
This simple example demonstrates the basic process of transforming XML data into HTML using XSLT. By creating an XML file with data and an XSLT file defining the transformation rules, you can use this method to generate dynamic HTML output from XML data.