Well, I finally caught up with the crowd and got JRuby running on one of my dev boxes. The reason I’d been interested in it from the getgo was because Ruby lacks any support for internal XSLT processing. All those system()s were starting to get me down, especially as I’m trying to get a DocBook->PDF rendering webservice to be a lot faster. Much to my surprise, I was able to get simple transforms working in almost no time (thanks in part to lots of help). Without further ado, here’s a simple library for XSLT transforms using either Xalan-J or Saxon (make sure you have the jars for both in your CLASSPATH):
require 'java'
module JXslt
include_class "javax.xml.transform.TransformerFactory"
include_class "javax.xml.transform.Transformer"
include_class "javax.xml.transform.stream.StreamSource"
include_class "javax.xml.transform.stream.StreamResult"
include_class "java.lang.System"
class XsltProcessor
def transform(xslt,infile,outfile)
transformer = @tf.newTransformer(StreamSource.new(xslt))
transformer.transform(StreamSource.new(infile), StreamResult.new(outfile))
end
end # XsltProcessor
class Saxon < XsltProcessor
TRANSFORMER_FACTORY_IMPL = "net.sf.saxon.TransformerFactoryImpl"
def initialize
System.setProperty("javax.xml.transform.TransformerFactory", TRANSFORMER_FACTORY_IMPL)
@tf = TransformerFactory.newInstance
end
end
class Xalan < XsltProcessor
TRANSFORMER_FACTORY_IMPL = "org.apache.xalan.processor.TransformerFactoryImpl"
def initialize
System.setProperty("javax.xml.transform.TransformerFactory", TRANSFORMER_FACTORY_IMPL)
@tf = TransformerFactory.newInstance
end
end
end
# if you wanted to run this from the command line, do something like
# $ jruby lib/jxslt.rb a.xsl in.xml out.xml
xalan = JXslt::Xalan.new
xalan.transform(*ARGV)
#saxon = JXslt::Saxon.new
#saxon.transform(*ARGV)
Big props to Charles for helping me get going and writing the first version of the above.
darcs get http://kfahlgren.com/code/lib/jxslt/ or jxslt.rb