Summary
This tutorial has demonstrated how you can use XSLT, controlled by the Ant build tool, to automatically generate both Java code and XSLT transformations.
The tutorial began by introducing the basic concepts behind code generation, reviewing its benefits and the advantages of using XML and XSLT to implement little languages that can be used to drive code generation processes. Also reviewed were some of the limitations of XSLT you might encounter when applying it to code generation, with a proposal that embedding the transformation within a build framework (such as Ant) can eliminate some of these limitations.
The remainder of the tutorial covered, in detail, two separate examples. The first of these explored the use of XSLT to generate Java code using a Bean Markup language. This example introduced the use of Ant, showing how you can use its sophisticated task management to control the multi-step processes required to generate, format, and ultimately compile Java code. The Jalopy source code formatter was also introduced as a means of applying consistent formatting to Java source code, removing the need to attempt this using XSLT.
The last section of the tutorial introduced the concept of meta-stylesheets -- XSLT transforms that generate other XSLT transforms. The XSLT technique of namespace aliasing was discussed as an essential part of implementing these transformations. The examples showed how you could map an Element Filter language describing operations to be carried out on XML elements to an XSLT implementation -- first by hand, and then using the meta-stylesheet technique. Again, Ant was used as a means to tie together the multi-step process by making the main filter transformation dependent on the meta-stylesheet transformation.
You can easily extend the techniques and framework introduced in this tutorial for use in generating other kinds of source code. You can also adapt them to the processing of more complex little languages that would allow the generation of more sophisticated Java code, including complete applications as well as more powerful XSLT transformations.
To learn more about how code generation is being used in real projects, consult the Resources for pointers to more information. For example, Schematron is a little language for validating XML documents implemented using XSLT and meta-stylesheets. The Cocoon project also includes a code generator that's used to convert XML documents, known as XML Server Pages, into Java code suitable for plugging into the Cocoon framework.


