Accessing a Database in Xalan

Xalan provides a set of extension functions that give us access to any JDBC data source. The extension functions we’ll use are sql:new() to create a new database connection, sql:query() to execute a query, and sql:close() to close the connection. In addition, we’ll use the function sql:disableStreamingMode() to get around a “feature” of the Xalan SQL library.

Here’s the stylesheet:

<?xml version="1.0"?>
<!-- xalan-sql.xsl -->
<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:sql="org.apache.xalan.lib.sql.XConnection"
  extension-element-prefixes="sql">

  <xsl:output method="html"/>

  <xsl:template match="/">

    <!-- Create the JDBC connection -->
    <xsl:variable name="books"
      select="sql:new('org.apache.derby.jdbc.ClientDriver', 
              'jdbc:derby://localhost:1527/books')"/>

    <!-- Workaround for a bug in Xalan’s SQL extension? -->
    <xsl:variable name="streaming"
      select="sql:disableStreamingMode($books)"/>

    <!-- Run the query -->
    <xsl:variable name="queryResults"
      select="sql:query($books, 'select * from doug.compbks')"/>

    <html>
      <head>
        <title>Computer books in our database</title>
      </head>
      <body style="font-family: sans-serif;">
        <h1>Computer books in our database</h1>
        <p>Here are the 
        <xsl:value-of select="count($queryResults/sql/row-set/row)"/>
        computer books we have in stock:</p>
        <table border="1" cellpadding="5">
          <tr>
            <xsl:for-each select="$queryResults/sql/metadata/column-header">
              <th>
 <xsl:value-of select="@column-label"/> ...

Get XSLT, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.