Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

  • Print
  • + Share This
From the author of

Outputting HTML Code

There are basically two kinds of components in an XSLT style sheet: instructions and literals. The XSLT instructions describe how the source XML document will be transformed. The literals-typically HTML code and text- are output just as they appear in the style sheet.

In your root template, you create the structure for the final transformed document. For HTML output, you'll want to add HTML header information , body , etc.) at the very least. And if you like, you can add extensive HTML formatting as well.

In templates other than the root template, you can add whatever HTML formatting is necessary to set up your output, but probably not the html , head , or body elements.

To add HTML code to the output:

Within a template rule tag (that is, between <xsl:template match="..."> and </xsl:template>, add the HTML code that you would like to output when that particular template is invoked.

Figure 7

Anything that is not an xsl instruction will be outputted as is. It's an easy way to add HTML coding and text. The HTML must be well-formed, e.g., the <p> tags must have matching </p> tags and I've used <hr/>and not <hr>.

Figure 8

The XSLT processor (Saxon, in this case) still hasn't gotten its hands on the XML but contents itself with outputting all of the HTML tags and text. Notice how Saxon adds the <meta> tag automatically, once it sees the <html> tag and realizes that we're out-putting HTML code. It also changes <hr/> back into the more recognized and better supported <hr>.

Tips

  • Your HTML code must adhere to XML rules for well-formedness. And while it doesn't have to be XHTML (the only additional change would be to write all your element and attribute names in lowercase letters), it's probably a good idea.

  • I don't specify what the match attribute is equal to in the instructions since you can add HTML output to any template, not just the root template.

  • You can actually create any kind of node this way. Anything that is not an XSL instruction is output as is in the final document.

  • You can also create elements (and attributes and text) by using xsl:element , xsl:attribute, and xsl:text , but they are a bit more complicated and generally reserved for special cases.

  • For more information about how to write HTML, you might want to consult my bestselling HTML 4 for the World Wide Web: Visual QuickStart Guide, Fourth Edition. For more information, jump to http://www.cookwood.com/html4_4e/.

    Figure 9

    Here's what it looks like so far in a browser. It's not very exciting yet, but we're getting somewhere.

  • + Share This
  • 🔖 Save To Your Account