Linkwerk Logo

invitation2xhtml.xslt - Transforming XML to XHTML

Up · XHTML · PDF · WordML

The input XML document is designed to be very simply. Since XHTML is simple too, it's not difficult to write an XSLT program to transform the XML. Before I describe the program you might want to try it. Everything you need is an XSLT engine, such as Xalan or Saxon. Then follow steps 1-3:

  1. Download the sample XML file invitation.xml

  2. Download the XSLT program invitation2xhtml.xslt (Download/View)

  3. Run the XSLT program on the sample data, for example: -IN ../invitation.xml -XSL invitation2xhtml.xslt -OUT invitation.html

You should get an XHTML file as the result of the transformation (invitation.html). Of course you can view it in your web browser. For those of you who don't have a web browser ;-) there's a screenshot of how it looks in mine:


If you downloaded the XSLT program, take a look at it. Besides of the root element stylesheet it contains just some templates for the element types of the sample XML data:

The Template for the root element invitation generates the global XHTML structure (html, head, body). Within the body it generates some text output and applies the templates for the other input elements at the appropriate points.

<xslt:template match="invitation">
Invitation to
<xslt:value-of select="event"></xslt:value-of>
<style type="text/css">
<div class="body">
<xslt:apply-templates select="event"></xslt:apply-templates>
<p class="meta">
I'd like to invite you to come to
<xslt:apply-templates select="location"></xslt:apply-templates>
. The event takes place on
<xslt:apply-templates select="date"></xslt:apply-templates>
<xslt:apply-templates select="time"></xslt:apply-templates>
<xslt:apply-templates select="description|dresscode"></xslt:apply-templates>

The template for events is simple: events become h1 elements (heading 1):

<xslt:template match="event">

The next template matches several elements: location, date and time. All these elements become inline elements in XHTML, marked up as span. To control the XHTML/CSS styling of those elements separately for each element type, I use the class attribute with a value of the original element type name. The local-name() function returns the element type name.

<xslt:template match="location | date | time">
<span class="{local-name()}">

para and emph are handled straight forward: They're getting transformed to p and em respectively:

<xslt:template match="para">
<xslt:template match="emph">

dresscode and description are not much more difficult to process: Both are prefixed by an appropriate text:

<xslt:template match="description">
<div class="description">
What's up?
<xslt:template match="dresscode">
<p class="dresscode">
What to wear?
© 2005, Stefan Mintert, All rights reserved