While adding REST support for Libraryfind, I found that I wanted to provide an output in XML, but that could also provide HTML if an XSLT was attached. In Rails, generating XML files is actually pretty easy. In Rails, output is specified in views. HTML views are created using a .rhtml extension, while xml views are created using a .rxml extension (at least, until Rails 2.0 when they are to change).
Anyway, we use libxml for XML processing of large XML documents (since I just have never found REXML up to the task) and was happy to find a gem based on libxml that provides XSLT support as well. The libxslt-ruby gem provides a very simplified method for doing XSLT processing in ruby. In the .rxml file, I add the following code:
if params[:xslt] != nil
@headers["Content-Type"] = "text/html"
xslt = XML::XSLT.file(params[:xslt])
xslt.doc = XML::Parser.string(_lxml).parse
# Parse to create a stylesheet, then apply.
s = xslt.parse
Simple and no fuss. The XML::XSLT.file function can take a physical or remote file location. To parse the file, you must pass into XML::XSLT.doc a reference to a XML::Document object. Since libxml doesn’t provide a function to deal with xml data directly (it assumes that you are loading XML via a file), you simply need to use the included XML Parser object to create an XML::Document object dynamically. Anyway, I’m finding that this works really well.