XSLT Cookbook, from O'Reilly. Chapter 8 XML to HTML | 17 | WebReference

XSLT Cookbook, from O'Reilly. Chapter 8 XML to HTML | 17

XSLT Cookbook, Chapter 8: XML to HTML

[The following is the conclusion of our series of excerpts from Chapter 8 of the O'Reilly title, XSLT Cookbook.]

Creating a Self-Contained HTML Transformation


You want to package XML data, as well as a stylesheet for converting it to HTML, into a single file.


This recipe assumes you have a browser that supports client-side XSLT transformations (IE 6.0, IE 5.x + MSXML 3.0, Netscape Navigator 6.0, etc.):

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="application/xml" href="selfcontained.xsl"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
<portfolio xmlns="http://www.ora.com/XSLTCookbook/namespaces/portfolio">
<xsl:output method="html" />
  <xsl:attribute-set name="gain-loss-font">
    <xsl:attribute name="color">
        <xsl:when test="(pf:current - pf:paid) * pf:qty >= 0">black</xsl:when>
<xsl:template match="xsl:stylesheet">
  <xsl:apply-templates select="pf:portfolio"/>
<xsl:template match="pf:portfolio">
      <title>My Portfolio</title>
     <body bgcolor="#FFFFFF" text="#000000">
      <table border="1" cellpadding="2">
<xsl:template match="pf:investment">
    <td><xsl:value-of select="pf:symbol"/></td>
    <td><xsl:value-of select="pf:current"/></td>
    <td><xsl:value-of select="pf:paid"/></td>
    <td><xsl:value-of select="pf:qty"/></td>
    <td><font xsl:use-attribute-sets="gain-loss-font"><xsl:value-of select="format-
number((pf:current - pf:paid) * pf:qty, '#,##0.00')"/></font></td>

Two elements in this stylesheet make it work.

The first is the xml-stylesheet processing instruction, which tells the browser that the stylesheet associated with the document it loads is the very same document. You can refer to the same document as its stylesheet with href="" rather than specifying the name of the file, which is helpful if you ever rename it.

The second is the template that matches the xsl:stylesheet element and redirects stylesheet processing to the embedded XML data. In this case, the elements are in the http://www.ora.com/XSLTCookbook/namespaces/portfolio namespace.

Created: March 27, 2003
Revised: May 5, 2003

URL: http://webreference.com/programming/xslt/cookbook/chap8/3