Easy way to migrate from JAXB to Castor?

601 Views Asked by At

I have created a library which includes some 200 Java classes generated from an existing XSD with JAXB like this:

xjc -no-header -d schemas -b xsd/binding.xml xsd

Alas, JAXB is not supported on Android, and the general suggestion seems to be to use a different library. Castor seems to be a suitable alternative—especially as it offers conversion of .xsd into Java classes. However, doing so seems to be more complex than in Java, and I have no idea of how much the result differs from xjc output.

My use case is unmarshaling and reading the unmarshaled data (changing data or marshaling are not needed). That is, there is a vast amount of code which relies on the resulting Java class schema, therefore any difference between xjc-generated classes and their Castor counterparts would mean a lot of refactoring.

Is there a simple recipe on how to generate Java classes from .xsd in Castor and get a result that is as close as possible to what xjc produces?

1

There are 1 best solutions below

0
user149408 On

The following approach is as close as I got, though some refactoring is still required:

Place a file named castorbuilder.properties on your classpath, with the following content:

org.exolab.castor.builder.javaclassmapping=type
org.exolab.castor.builder.javaVersion=5.0
# Replace the following lines with your schema(s)
org.exolab.castor.builder.nspackages=\
   http://example.com/schema/foo=com.example.schema.foo,\
   http://example.org/schema/bar=org.example.schema.bar
org.exolab.castor.builder.primitivetowrapper=true

Then run the following command line:

java -cp "*" org.exolab.castor.builder.SourceGeneratorMain -i schema.xsd -types j2

In the above, replace the classpath with the path to the Castor JAR files and castorbuilder.properties, and replace schema.xsd with the path to your XSD file.

Of course, you can invoke Castor via Ant or Maven—in this case, be sure to use the respective equivalent to the command line options above and make sure the properties file is picked up.

Differences which require refactoring:

  • Enum types are now in their own types sub-package
  • Where XML Enum literals are in camelCase, they now become CAMELCASE rather than CAMEL_CASE
  • Castor generates array properties where JAXB has Collection properties
  • Some class names get an underscore as a prefix; apparently JAXB drops those while Castor preserves them
  • Date fields are now Date instances
  • In one instance a property changed its name from value to content

However—there seems to be a bug in Castor, as some of the generated classes invoke a non-existent constructor. This has stopped me from successfully trying this out; I only got as far as refactoring my existing code to the point of being free from syntax and compiler errors.