An XSLT style sheet can emit HTML <STYLE>
elements, including CSS specifications, directly into the HTML that results from the XSLT transformation. This option works best when the number of CSS rules is small and easily managed.
To place a <STYLE>
element and its CSS rules into the result tree of a transformation, you can include them in the XSLT template that instantiates the HTML <HEAD>
element. The book.xsl file below illustrates this.
In book.xsl, the first template rule matches the root element of the XML document, <book>
. When it finds a match in the source tree, it instantiates <HTML>
and <HEAD>
elements in the result tree.
The <HEAD>
element includes both a <TITLE>
element and a <STYLE>
element. The <STYLE>
element includes a single CSS rule, which says to display all <H1>
elements in the result tree in the indicated font.
Finally, this template rule says to instantiate a <BODY>
element, and then to process any children of the matching <book>
element. This is the purpose of the <xsl:apply-templates/>
element. During this process, the template rule also checks for other matching template rules, and transforms them as necessary.
The second template rule is invoked by the <xsl:apply-templates/>
element of the first template rule. This second template rule instantiates an <H1>
element. The content of the <H1>
element is that of a <book_title>
element in the source tree.
The result of applying this transformation to the sample source document is shown below.
Example
XML File (book.xml)
<?xml version='1.0'?>
<?xml-stylesheet type="text/xsl" href="book.xsl" ?>
<book>
<book_title>Jambing on the Trixles</book_title>
<author> Randall, Tristan</author>
</book>
XSLT File (book.xsl)
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="book">
<HTML>
<HEAD>
<TITLE>Book Info</TITLE>
<STYLE>
H1 {font-family: Arial,Univers,sans-serif;
font-size: 36pt }
</STYLE>
</HEAD>
<BODY><xsl:apply-templates/></BODY>
</HTML>
</xsl:template>
<xsl:template match="book_title">
<H1><xsl:value-of select="."/></H1>
</xsl:template>
</xsl:stylesheet>
XSLT Processor Output
<HTML>
<HEAD>
<TITLE>Book Info</TITLE>
<STYLE>
H1 {font-family: Arial,Univers,sans-serif;
font-size: 36pt }
</STYLE>
</HEAD>
<BODY><H1>Jambing on the Trixles</H1> Randall, Tristan</BODY>
</HTML>