jastrachan | 29 Mar 19:32 2004
Picon

Re: Thoughts on Groovy XSLT


On 29 Mar 2004, at 17:00, Shakeel Mahate wrote:
> What with James abandoning the XML pointy bracket religion as a  
> solution for
> writing programs, I have been thinking about by 10,000 line functional
> programs written in the erstwhile XSLT stylesheets.

:)

> I like the XSLT programming model, however I dislike the syntax.

Agreed. I think XPath is the coolest part of XSLT.

> Has anybody thought along the following lines to migrate XSLT  
> stylesheets to
> Groovy?
>
> package groovy.xslt
>
> class XsltProcessor {
>    MarkupBuilder process(stylesheet, inputElementNode) {
>        // Applies the stylesheet to the Dom.Element and generates  
> output
>        // MarkupBuilder
>    }
> }
>
> package groovy.xslt
>
> class XsltStylesheet extends MarkupBuilder {
>    // This would be the replacement for XSLT Stylesheets
>    // Would have a notion of templates with patterns, named templates
>    // functions and a true programming syntax
>    // Xslt Stylesheet parameters would be instance variables
>    // XsltProcessor would visit nodes in the inputElementNode and fire
>    // the appropriate template
> }
>
> The users would have to subclass XsltStylesheet to write their own
> stylesheets.

BTW XSLT is actually quite flat - you just register templates with a  
stylesheet, so maybe just a 'template' method is required on some  
Groovy object - i.e. builders are more for hierarchic data structures -  
if the body of a template were a closure, then a Stylesheet would be  
flat.

>
> Are there any interested parties?
>
> Does this make sense?

Sure, sounds like fun.

> How would one go about implementing this in Groovy, James could you  
> drop
> some hints for a beginner?  Where should I peek to get more ideas to
> implement this darn thing?

Incidentally I wrote a little script to convert HTML into wiki markup...

http://radio.weblogs.com/0112098/2004/01/13.html

which works quite similar to XSLT...

http://cvs.groovy.codehaus.org/viewcvs.cgi/groovy/groovy-core/src/test/ 
org/codehaus/groovy/wiki/Html2Wiki.groovy?rev=HEAD&view=auto

this script actually parses HTML rather than XML but its still using a  
SAX parser so would work equally well on XML too. The main loop in the  
script is a switch statement which then performs some logic and  
traverses its children.  I guess you could make a generic version of  
this, where closures are registered for patterns. e.g.

stylesheet.template("p") { println it; stylesheet.applyTemplates(it) }

etc.

FWIW I wrote a little XSLT matching engine in dom4j...

http://dom4j.org/apidocs/org/dom4j/rule/package-summary.html

which pretty much implements the core XSLT matching/processing model.  
Using this library you could register patterns & actions (the actions  
could be implemented as closures).

James
-------
http://radio.weblogs.com/0112098/

Gmane