XSLT (Extensible Stylesheet Language Transformations) is a language used for transforming XML documents into different formats. It allows you to define templates and rules for how XML elements should be converted into other markup languages such as HTML, XHTML, or even XML itself.
Here's a simple explanation with an example:
Suppose you have the following XML document representing information about books:
Example
<library> <book> <title>The Great Gatsby</title> <author>F. Scott Fitzgerald</author> <year>1925</year> </book> <book> <title>To Kill a Mockingbird</title> <author>Harper Lee</author> <year>1960</year> </book> </library>
And you want to transform this XML document into an HTML list of books. You can use XSLT to accomplish this:
Example
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>Book List</h2> <ul> <xsl:for-each select="library/book"> <li> <xsl:value-of select="title"/> by <xsl:value-of select="author"/> (Year: <xsl:value-of select="year"/>) </li> </xsl:for-each> </ul> </body> </html> </xsl:template> </xsl:stylesheet>
In this XSLT example:
<xsl:stylesheet>
declares the XSLT stylesheet and specifies its version and namespace.<xsl:template match="/">
defines a template that matches the root node of the XML document.<xsl:for-each select="library/book">
is an XSLT instruction that iterates over each <book>
element in the XML document.<xsl:value-of select="title"/>
, <xsl:value-of select="author"/>
, and <xsl:value-of select="year"/>
are used to extract the values of the <title>
, <author>
, and <year>
elements, respectively.When you apply this XSLT transformation to the XML document, it will produce the following HTML output:
Example
<html> <body> <h2>Book List</h2> <ul> <li>The Great Gatsby by F. Scott Fitzgerald (Year: 1925)</li> <li>To Kill a Mockingbird by Harper Lee (Year: 1960)</li> </ul> </body> </html>
XSLT is a powerful tool for transforming XML documents into various formats, allowing you to tailor the output to your specific needs