Maybe it’s just my long history with the technology, but I often find XSLT a convenient technology for manipulating XML. When I scrape a Web page with the WSO2 Mashup Server, I generally use XSLT to extract and manipulate the values (e.g. my National Geographic Picture of the Day Feed mashup which I described here). I find it performs better than extracting values individually through an XPath or RegExp filter or through E4X itself.
But what about when you’re not scraping a page? While E4X does most XML manipulation tasks pretty well, it doesn’t provide some higher-level functions such as sorting. The last thing I want to do is implement a sorting algorithm in Javascript, when XSLT already does the task very well.
The Mashup Server doesn’t have direct access to an XSLT processor, but you can use the Scraper object to execute a transformation even without performing a scrape.
Here’s a simple function that you can add to a mashup to support transformations inside your mashup.
transform.visible = false;
function transform(source, stylesheet) {
var config =
<config>
<var-def name=’response’>
<xslt>
<xml>
<template>{source.toXMLString()}</template>
</xml>
<stylesheet>
<template>{stylesheet.toXMLString()}</template>
</stylesheet>
</xslt>
</var-def>
</config>;var scraper = new Scraper(config);
var result = scraper.response;// strip off xml declaration and any PIs, E4X can’t parse them
while (result.indexOf("<?") == 0)
result = result.substring(result.indexOf("?>")+2);return new XML(result);
}
Usage is simple:
var xslt = <xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
…
</xsl:stylesheet>;var xml = <source/>;
var result = transform(xml, xslt);
Note that the function strips of any XML declarations or leading processing instructions, but you can (and should) also include <xsl:output method="xml" omit-xml-declaration="yes"/> inside your XSLT to make that extra cleanup step unnecessary. Enjoy!
Posts (RSS)