Let's break down the concept of an XSLT <template>
in a simple way, along with an example:
XML (Extensible Markup Language): XML is a markup language used to store and structure data. It's hierarchical and uses tags to define elements and their relationships.
XSLT (eXtensible Stylesheet Language Transformations): XSLT is a language for transforming XML documents into different formats, such as HTML, XML, or plain text. It uses templates to define how different parts of an XML document should be transformed.
<template>
ExplainedIn XSLT, <template>
is used to define rules for transforming specific parts of an XML document. Each <template>
specifies what should happen when the XSLT processor encounters certain XML elements or conditions.
Let's consider an XML document representing a list of books:
Example
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="fiction"> <title>Harry Potter</title> <author>J.K. Rowling</author> <year>2005</year> </book> <book category="non-fiction"> <title>Introduction to XML</title> <author>John Doe</author> <year>2010</year> </book> </bookstore>
Suppose we want to transform this XML into an HTML list (<ul>
) of book titles only. We can use XSLT <template>
to achieve this:
Example
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- Template to match the root element --> <xsl:template match="/"> <html> <body> <h2>Book List</h2> <ul> <!-- Apply the 'book' template for each 'book' element --> <xsl:apply-templates select="bookstore/book"/> </ul> </body> </html> </xsl:template> <!-- Template to match 'book' elements --> <xsl:template match="book"> <li> <xsl:value-of select="title"/> </li> </xsl:template> </xsl:stylesheet>
XSLT Structure:
<xsl:stylesheet>
defines the XSLT document with its version and namespace.xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
declares the XSLT namespace.Templates:
<xsl:template match="/">
: This template matches the root element of the XML document (/
). It defines the structure of the HTML output.
Inside this template, <xsl:apply-templates select="bookstore/book"/>
applies the <book>
template to each <book>
element under <bookstore>
.
<xsl:template match="book">
: This template matches each <book>
element. It specifies that for each <book>
encountered, an <li>
element should be created in the HTML output containing the value of the <title>
element (<xsl:value-of select="title"/>
).
When this XSLT transformation is applied to the XML document provided earlier, the output HTML will be:
Example
<html> <body> <h2>Book List</h2> <ul> <li>Harry Potter</li> <li>Introduction to XML</li> </ul> </body> </html>
<template>
in XSLT specifies rules for transforming XML elements.In the example, we used <template>
to define how to transform <book>
elements into an HTML list of book titles. This demonstrates the basic usage and power of XSLT templates in transforming XML data into various output formats.