XSLT and Ruby/Rails
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"
require 'xml/libxml'
require 'xml/libxslt'
xslt = XML::XSLT.file(params[:xslt])
xslt.doc = XML::Parser.string(_lxml).parse
# Parse to create a stylesheet, then apply.
s = xslt.parse
s.apply
return s.to_s
else
return _lxml
end
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.
–TR
No comments yet.
Leave a comment
Categories
- Access 2006
- ALA Midwinter 2007
- ALA Summer 2007
- Book
- C#
- Code4Lib 2007
- Code4Lib2008
- Conferences
- CONTENTdm
- Cycling
- Digital Libraries
- Dspace
- Education
- Family
- General Computing
- Innovative Interfaces
- Java
- LibraryFind
- MarcEdit
- Microsoft
- NWIUG 2006
- OAI
- OCLC
- Open Library
- OSCON 2006
- Patent Stupidity
- Programming
- rails
- Readex
- Readex 2006
- ruby
- Running
- Simpsons
- Travel
- Uncategorized
- Wii
- Wikipedia
Archive
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- May 2007
- April 2007
- March 2007
- February 2007
- January 2007
- December 2006
- November 2006
- October 2006
- September 2006
- August 2006
- July 2006
- June 2006
- May 2006
- April 2006
- March 2006
- February 2006
- January 2006
- December 2005
- November 2005
- October 2005
- September 2005
- August 2005
- July 2005