Doing XSL Transforms with Greasemonkey 2

Posted by dacc on February 25, 2009

I’ve been struggling to make the XML build logs in our CruiseControl Dashboard legible, and finally ended up going with an XSLT transform via Greasemonkey.

Even this took a little doing, and so I thought I would share how to perform an arbitrary XSL transform on a loaded XML/XHTML document with a userscript.

Here’s the script I ended up with.

// ==UserScript==
// @name CruiseControl Log Converter
// @namespace http://rieke-server.physiol.washington.edu/gmonkey
// @description Transform CruiseControl XML build logs into legible HTML.
// @include http://*/tab/build/download/log/*/*.xml
// @resource xslt http://rieke-server.physiol.washington.edu/stylesheet/cclog2html.xslt
// ==/UserScript==
 
var xslt = new DOMParser().parseFromString(GM_getResourceText("xslt"),
  "text/xml");
 
var processor = new XSLTProcessor();
processor.importStylesheet(xslt);
 
// not sure why this temporary doc is needed, but thanks to Toru Watanabe
// on userscripts.org for making this apparent.
var tmpdoc = document.implementation.createDocument("", "", null);
var fragment = processor.transformToFragment(document, tmpdoc);
document.replaceChild(fragment, document.documentElement);

Ok, so this script:

  1. Defines a resource called “xslt” that will be retrieved and cached on installation. Note that if users are to upgrade your script, you must assign a new URL to any changed resource file. The file is cached only once!
  2. Loads the resource and configures an XSLT processor.
  3. Performs a transform to a document fragment, which is then used to replace the root element of the current document.

I found a couple examples on-line, but this ended up being much more succinct. The first example did the transform, and then serialized the resulting DOM into a string and accessed it using a “data:” URI. The other is the same basic idea as my version, but instead of replacing the root element appended to it and manually removed all the siblings of the new element (leaving the source root element in place).

I’ll probably post a finished version of this one for CC at some point…

Trackbacks

Use this link to trackback from your own site.

blog comments powered by Disqus