XSLT

Code Generation

XSLT Code Generation is not were XSLT was made for. However, it has turned out that XSLT can be a good tool for code generation if you can describe the essential aspects, e.g. design, metadata, or framework, of your target code in XML. XSLT was specifically made for processing XML. Based on XML input and an appropriate XSLT stylesheet any XSLT processor can be used to generate code, either in plain text source code form (e.g. Java) or again in XML form (e.g. XSLT code).

XSLT Code Generation - producing XSLT Stylesheet Code

An XSLT stylesheet itself is also an XML document. This has a nice, often useful side-effect. It means any XSLT stylesheet can be transformed but also generated by another XSLT stylesheet. XSLT itself can thus be used to generate new XSLT code. Some examples of XSLT Code Generation projects:

XSLT Code Generation - producing Source Code

XSLT can also be used to generate code for other programming languages like Java, C++ or C#. XSLT Code Generation can succesfully be applied in those cases where following holds:

  • You are writing similar chunks of code repetitively, but you can not solve this by using some common method, or you need to write slightly different code for multiple deployment platforms
  • You already have or can generate a description of the domain specific metadata (Domain Specific Model) of your target in the form of an XML file
    • e.g. a XMI representation of a UML design
    • e.g. a XUL or XAML description of a user interface design
    • e.g. a WSDL description of an XML Web Service
    • e.g. some configuration file
    • or some other home-made XML description of the metadata of the "thing" you want to generate code for
  • You can imagine and write down some sort of recipe how to generate code from this metadata description

The process of creating a XSLT Code Generation solution for producing source code goes roughly as follows:
  1. Create a metadata description of some example in XML
  2. Write down the code you would like to be generated for the example
  3. Write one or more XSLT Code Generation stylesheet that generate the example code
  4. Generalize and improve your XSLT stylesheet
    • driven by extension of your example
    • while improving your XML description (and in case of a home-made XML description, specifying its schema, i.e. its generalized syntax, using XML Schema language)
  5. It is often also quite useful to write an additional stylesheet that generates (HTML)documentation from your XML metadata file.

Some examples of XSLT Code Generation based automated source code production projects and articles:

Code generation in general

More info on code generation in general:

Tools

Some tools that may turn out helpful when diving into XSLT based code generation:
  • MetaCoder - an IDE for XML/XSLT Code Generators
  • Ejen - Java/XML/XSLT text generation system, eases creation of XSLT based code generators