Compile XSD files into Java classes using XJC with Gradle and Kotlin

Niel de Wet
1 min readJul 25, 2019

--

I couldn’t find any good resources on how to generate Java (or Kotlin) code from XSD schema files during a Gradle build of a Kotlin JVM project, so here’s quick summary.

Tools

  • xjc — Underlying tool to compile an “XML schema file into fully annotated Java classes.”
  • org.unbroken-dome.xjc gradle plugin —Use xjc to generate code as part of the build.

build.gradle

Add the following sections to your build file:

id 'org.unbroken-dome.xjc' version '1.4.3'

The above needs to be added to the plugins closure to add the plugin to the build.

xjc {                           
includeInMainCompilation = false
}

sourceSets {
main { java { srcDir xjcGenerate.outputDirectory } } }
compileKotlin {
dependsOn xjcGenerate
}

By default gradle will execute the compileKotlin task before compileJava and also before xjcGenerate (added by the plugin). To ensure the generated code can be referenced from your Kotlin code during the build you need to add it to the main.java source set and ensure that xjcGenerate happens before the Kotlin code is compiled.

Java 11

In Java 11 JAXB (and the xjc tool) was removed. To use it since Java 11 add this dependency:

implementation 'javax.xml.bind:jaxb-api:2.3.1'

Feedback

Do you have improvements or an alternative method to achieve this? I would love to hear from you!

Here is complete and minimal setup. It’s a vanilla Kotlin application generated with gradle init. My additions are marked with /* comments like this */ and assumes an *.xsd file in the default location (src/main/schema).

Lastly, you can upvote issue #20.

--

--

Responses (1)