Generating Java classes using JAXB 2.0

author's avatar
Kees de Kooter
Jun 4 19:36 • 1 min read

Use the proper hammer

Rather than hammering at the command line I decided to evaluate the JAXB Workshop https://jaxb-workshop.dev.java.net/. More specifically the Milano explorer. This GUI is a nice albeit still a bit buggy XSD browser and frontend for the JAXB compiler XJC. It allows you to browse an xsd and its dependent xsds in both source and schematic view.

Deal with snags in the source XSDs

One of the XSDs I am handling uses an underscore prefix as a naming convention for abstract elements. JAXB chokes on this, reporting a collision with a non-prefixed element. The JAXB specification explains why:

6.5.3 Underscore Handling
This section applies only when XML names are being mapped to a legal Java Identifier by default. In this case, the treatment of underscore is determined by underscoreBinding. If underscoreBinding is "asWordSeparator", then underscore must be treated as a punctuation character; otherwise if underscoreBinding is "asCharInWord", then underscore must be treated as a character in the word. The default value for underscoreBinding is "asWordSeparator".

We need to put this in an external binding customization file with extension .xjb. This file can be fed to the JAXB compiler using the -b switch.

<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"  xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0">

     <jaxb:bindings schemaLocation="A.xsd">
          <jaxb:globalBindings underscoreBinding="asCharInWord"/>
     </jaxb:bindings>

</jaxb:bindings>

Changing hammers

Unfortunately the JAXB workshop does not support external binding customization files yet (at least I do not have a clue how). So back to the command line.

xjc schema-name.xsd -b