Friday, July 9, 2010

Getting MySQL data into XML easily

I have been experimenting with XML lately and have found a great article for using XSLT to make an html table using an sql query from a database.
http://blog.mclaughlinsoftware.com/2008/08/29/querying-oracle-directly-from-xml/
It will use some of the instructions from this blog post:
download Xalan and unzip it to C:/xalan-j_2_7_1
http://xml.apache.org/xalan-j/downloads.html
Then download the mysql J connector:
Go into the zip and take it out and put it in the xalan folder
Mine was put here:
C:/xalan-j_2_7_1/mysql-connector-java-5.1.13-bin.jar
Next make an xsl file and name it mysql.xsl and put this in it:

<?xml version="1.0"?>
<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="/">
<xsl:variable
name="movies"
select="sql:new('com.mysql.jdbc.Driver','jdbc:mysql:///storedb','student','student')" />
<xsl:variable name="streaming" select="sql:disableStreamingMode($movies)" />
<xsl:variable
name="queryResults"
select="sql:query($movies,'SELECT i.item_title, i.item_asin, i.item_release_date FROM storedb.item i')" />
<html>
<head><title>MySQL Result Set</title></head>
<body style="font-family: sans-serif;">
<table border="1" cellpadding="5">
<tr>
<xsl:for-each select="$queryResults/sql/metadata/column-header">
<th><xsl:value-of select="@column-label" /></th>
</xsl:for-each>
</tr>
<xsl:apply-templates select="$queryResults/sql/row-set/row" />
</table>
</body>
</html>
<xsl:value-of select="sql:close($movies)" />
</xsl:template>
<xsl:template match="row">
<tr><xsl:apply-templates select="col" /></tr>
</xsl:template>
<xsl:template match="col">
<td><xsl:value-of select="text()" /></td>
</xsl:template>
</xsl:stylesheet>

Next run these commands from command prompt:
set CLASSPATH=%CLASSPATH%;C:\xalan-j_2_7_1\xalan.jar;.
set CLASSPATH=%CLASSPATH%;C:\xalan-j_2_7_1\serializer.jar
set CLASSPATH=%CLASSPATH%;C:\xalan-j_2_7_1\xercesImpl.jar
set CLASSPATH=%CLASSPATH%;C:\xalan-j_2_7_1\xml-apis.jar
set CLASSPATH=%CLASSPATH%;C:\xalan-j_2_7_1\xsltc.jar
set CLASSPATH=%CLASSPATH%;C:\xalan-j_2_7_1\mysql-connector-java-5.1.13-bin.jar
java org.apache.xalan.xslt.Process -XSL mysql.xsl > mysql.html
Now you should have an html document called mysql.html all ready to look at in a browser with the database tables showing in html format.
I will show an example:

item_titleitem_asinitem_release_date
"Good Eats with Alton Brown, Vol. 6 (3 - Pack): Tossed Around, Veggie Eats, Breakfast Eats 2"143499
"Good Eats with Alton Brown Vol. 8, Delicious Dishes (3 - Pack): Condiment Nation, Ocean Edibles 2, Veggie Eats 2"143510
Sports Medicine Imaging DVD: Single User477044
Musculoskeletal MRI DVD: Single User477087

No comments: