If you ever had a need to generate Java beans from the XSD by Castor, you probably have used Castor's SourceGenerator class (org.exolab.castor.builder.SourceGenerator
). Unfortunately, this main style class can not be easily integrated into the Ant driven build process (and, from my experience, 90% of projects out there use Ant). For example, SourceGenerator can process only one XSD schema at a time, and can't generate Java beans from multiple files.
This problem can be solved by using custom Ant task, which provides convinient way of running Castor's SourceGenerator on single file, directory, or a fileset:
<castor file="schema.xsd" todir="build/src" package="com.foo.bar" warnings="false" types="j2"/> <castor dir="schemas" todir="build/src" package="com.foo.bar" warnings="false" types="j2"/> <castor todir="build/src" package="com.foo.bar" warnings="false" types="j2"> <fileset dir="schemas"> <include name="*.xsd"/> </fileset> </castor>
Don't forget to declare the task with:
<path id="class.path"> <pathelement location="ant-optional-castor-20040412.jar"/> <pathelement location="castor-0.9.5.3-xml.jar"/> <pathelement path="${java.class.path}"/> </path> <taskdef name="castor" classname="org.apache.tools.ant.taskdefs.optional.castor.Castor" classpathref="class.path"/>
Source for the Castor Ant task can be found as attachement to the Bug# 885 in Castor's Bugzilla. Task accepts following parameters (they mostly correspond to SourceGenerator's arguments):
j2
makes Castor use Java2 collections