Suppose that you want to display your company information and sales data in a format that is more readable than the default tree view in Internet Explorer. You can do this by creating the following XSLT file, Transform.xsl. This file transforms the heading data values in the Sales.xml file into a well structured HTML format. The basic operations involve retrieving the data values of the specified elements or attributes. In XSLT, you use XPath pattern matching to do this. This is illustrated in Transform.xsl by use of the match
and select
attributes of the xsl:template
and xsl:value-
of elements, respectively. Notice how XPath expressions are constructed, in bold below, to reference element content and an attribute value.
To create the Transform.xsl file
<?xml version='1.0'?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html"/> <xsl:template match="/"> <html> <head> <!-- Referencing a data value as element content: --> <title><xsl:value-of select="//summary/heading"/></title> </head> <body> <h1><xsl:value-of select="//summary/heading"/></h1> <h2><xsl:value-of select="//summary/subhead"/></h2> <p><xsl:value-of select="//summary/description"/></p> <DIV> Region: <xsl:value-of select="//data/region[1]/name"/> </DIV> <!-- Referencing a data value as an attribute value: --> <DIV> First quarter sales: <xsl:value-of select="//data/region[1]/quarter/@books_sold[1]"/> </DIV> </body> </html> </xsl:template> </xsl:stylesheet>
To specify the XSLT file to use with the XML file
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="transform.xsl"?>
This processing instruction identifies Transform.xsl as the XSLT file to be used for transforming Sales.xml.
To view the transformation results
<summary>
element, as well as the first quarter results of the West Region.At the beginning of Transform.xsl, the xsl:stylesheet
line declares that this is an XSLT file. The xsl:output
line tells the XSLT processor to produce HTML output instead of the default output method of "xml".
The xsl:template
and xsl:value-of
lines use the XPath expressions to pick out the content of an element and an attribute value. For example, <xsl:template match="/">
defines a template rule for the root element of the source XML document and all of its children. <xsl:value-of select="//summary/heading"/>
returns the content of the <heading>
element contained in the <summary>
element. The <xsl:value-of select="//data/region[1]/quarter/@books_sold[1]"/>
returns the value of the books_sold
attribute for the first quarter in the first region, as ordered in the source document. The HTML tags format the retrieved data values.
Now you know how to select a given element, its content, or its attribute value. The next exercise shows how to Use CSS in XSLT.