May 26

XML – XSL Transformation in Browsers

Filed under: Playground | Taged as: , , | Comments Off

Extensible Stylesheet Language, or short XSL, is a family of related technologies designed to transofrm XML data.
This definition may seem not very spectecular, but the truth is far from the matter. XSLT is an often unused and underestimated technology. Current browsers like IE and Firefox have an integrated XSLT parser and are fully capable of doing tranformations on their own. Using XSLT in browsers is very straight forward and opens the door for a lot of nice and handy ideas.

The core elements of browser based XSL are:

  • XSL Transformations (XSLT): to transform XML documents into another format
  • XPath: to access specific data in XML structures
  • CSS: for formating the result documents

Data exchange with XML is daily work and with browser being capable of doing the transformation on their own, XSLT is no longer limited to server-side solutions. Direct integration of XML documents in web-applications or websites is no longer a troublesome way.

XSLT with browsers enhances the often practiced seperation of content and layout. While leaving the layout to XSL and CSS stylesheets, the content can be logically structured in a self-defined XML document. This makes a backend conversion unnecessary. The same structures can be used for printing an article or showing it’s text on the web. Using XPath also enriches the document as additional structures and blocks can be created on the fly and dynamically.

The following example shows a simple stylesheet to transform a list of articles to a corresponding HTML representation, styled with CSS. The table of contents on top of the site is generated automatically – another nice feature of XSL showing how powerful this technology is. This snippet shows the template definitions for creating the table of contents and the listing of all articles.

<xsl:template match="article">
        <xsl:variable name="category" select="@category"/>
        <xsl:variable name="id" select="@id"/>
        <div>
        <a name="{$id}"/>
        <h3><xsl:value-of select="title"/></h3>
        <xsl:value-of select="description"/>
        <br/>
        Published on <xsl:value-of select="date"/> in <xsl:value-of select="$category"/>
        </div>
    </xsl:template>
   
    <xsl:template match="title">
        <xsl:variable name="id" select="../@id"/>
        <xsl:variable name="time" select="../date/@timestamp"/>
        <li>
        <a href="#{$id}"><xsl:apply-templates/></a>
        <xsl:choose>
            <xsl:when test="$time < 1000">
<xsl:text> </xsl:text><span class="new">new!</span></xsl:when>
        </xsl:choose>
        </li>
    </xsl:template>

</xsl:stylesheet>

Check out the XSLT transfotmation or Download the XSL Browser Transformation

Comments are closed.