Generating JAXB classes with xjc

When working with Java and XML there is a number of frameworks that support working with that technology. Furthermore when working with an already working api there must be code in order be able to convert Java objects into XML and vice versa. Using xjc is an easy way to generate Java classes in order to “talk” XML.

Using xjc directly

Simply execute xjc in the bin folder of java. Then depending on the naming scheme of your schema package name and class names will be genereated. An customized output folder (-d), a binding file (-b) and a custom package (-p) can be given as parameters. When giving binding files, each file must be added seperatly via the option -b

xjc -d outputFolder -b bindingFile -p destinationPackage schemaName.xsd

For further options please have a look at the xjc documentation.

Using maven

In order to use xjc with maven simply use the jaxb2-maven-plugin. It provides the goal xjc that generates java source files by giving xsd schemas.

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>jaxb2-maven-plugin</artifactId>
  <version>1.6</version>
  <executions>
    <execution>
      <id>jaxbGeneration</id>
      <goals>
        <goal>xjc</goal>
      </goals>
      <configuration>
        <schemaDirectory>${basedir}/pathToSchema</schemaDirectory>
        <schemaFiles>schemaName.xsd</schemaFiles>
      </configuration>
    </execution>
  </executions>
</plugin>

Furthermore it is possible to use binding files to solve problems when generating java source. In case there are qualifiers that are not java compatible or when using different versions of a schema at the same time that might help to generate all of the sources in parallel packages or with different names, …
Using binding files is possible by simply adding the following lines to the configuration section.

${basedir}/pathToBindings

  elementbinding.xjb

For further options please have a look at the jaxb2-maven-plugin documentation

Sources

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.