A Simple Template

Let’s continue by looking at a simple example. Imagine that we have a directory called /src which includes some number of java files. There are numerous files which represent either simple classes or those that extend other classes. There could also be a few classes that implement various interfaces. We’d like to design a template that will parrse through the files and return specific information about the classes back to us. Consider the following template:

<XDtClass:forAllClasses type="AbstractNode">
<XDtProperty:forAllPropertiesWithTag tagName="node.attribute">
Node Field = <XDtMethod:propertyName/>

This simple template includes two different types of template tags: block and content. The first tag <XDtClass:forAllClasses> is a block tag and is designed to parse through all of the files supplied to the template. The tag as displayed is designed to check all of the classes within the supplied files and remove all of these where the class is not of type AbstractNode. After the parsing, we will be a set of files with classes that are of type AbstractNode. Next, a content tag <XDtClass:className> displays the name of the class. Then we have another block tag <XDtProperty:forAllPropertiesWithTag> that will parse through the remaining classes and display the name of all property with the tag @node.attribute. Thus, consider the following class snippet:

* @node.attribute name=popularity
* @node.attribute name=raid
public class MyNode extends AbstractNode {

The result of this class will be the output

Classname = MyNode Node Field = popularity Node Field = raid

We can see the different levels of looping within the template. The forAllClasses acts as an outer loop and the forAllPropertiesWithTag is an inner loop because it appears within the forAllClasses tag. We can activate this template using the following Ant target:

<target >
<templatedoclet destdir="test">
<fileset dir="${src}">
<include name="**/*.java"/>
<template templateFile="template/nodetemplate.xdt"

This Ant task will use a generic XDoclet Task defined in xdoclet.DocletTask to execute our template. We’ve defined a <fileset> to only pass in files with a java extension. The template to use for the code generation is defined by the templateFile attribute of the <template> element. The result of the parse and applicatino of the template will be output into the file test.txt.