May 09, 2003

Processing XML configuration files using XSLT

Java | XSLT
Guardian at the Japanese Garden in Huntington Library, Pasadena CA

Charles Miller decided to use Scheme to describe configuration files instead of XML.

I have a different approach. Since most of the applications I write these days end up processing XML anyways, I prefer writing XML configurations file. Since I really like XSLT's power and to avoid the proliferation of tools like commons-digester and others, I write a simple XSLT stylesheet to process my configuration files. Such a stylesheet would need to receive as parameter a context Java object which needs to be initialized according to the configuration file.

The object initialization could be written in simple XSLT templates. Using Charles' example, lets say we have a hypothetic add-module XML element with a module attribute. We'd like to have a MyClass instance that gets invoked with a addModule method and passed the string value of module. The following XSLT stylesheet would do it:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:MyClass="java:some.package.MyClass">

<!-- This is the MyClass instance to be initialized -->
<xsl:param name="context"/>

<xsl:template match="add-module">
<xsl:value-of select="MyClass:addModule($context, @module)"/>
</xsl:template>

</xsl:stylesheet>

An instance of MyClass would need to be passed as parameter to the XSLT stylesheet from the Java side of the world. This can be set using the Transformer.setParameter(String, Object) method.

XSLT comes for free in Java 1.4, so there is no memory overhead from using XSLT. Even so, I still prefer Saxon over Xalan 2.3.1 that is distributed in JDK 1.4.

Posted by ovidiu at May 09, 2003 01:01 AM |
 
Copyright © 2002-2016 Ovidiu Predescu.