Generate kotlin classes from xsd

Viewed 2899

There is an xsd schema. It is necessary to generate Kotlin-classes according to the xsd description. How can I do this? Using the code below, I can get java classes. But I need kotlin classes

plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.3.21'
    // Apply the application plugin to add support for building a CLI application.
    id 'application'
    /* Generate Java code from XSD */
    id 'org.unbroken-dome.xjc' version '1.4.3'
}
group 'org.example'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
xjc {
    includeInMainCompilation = false
}
xjcGenerate {
    source = fileTree('src/main/schema') { include '*.xsd' }
    bindingFiles = fileTree('src/main/jaxb') { include '*.xjb' }
    catalogs = fileTree('src/main/catalog') { include '*.cat' }
}
sourceSets {
    main { java { srcDir xjcGenerate.outputDirectory } }
}
compileKotlin {
    dependsOn xjcGenerate
}
/* END: Make xjcGenerate work with Kotlin */
repositories {
    // Use jcenter for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
    mavenCentral()
    google()
}
dependencies {
    /* Add JAXB dependencies for Java 11 */
    implementation 'javax.xml.bind:jaxb-api:2.3.1'
    // Use the Kotlin JDK 8 standard library.
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
    // Use the Kotlin test library.
    testImplementation 'org.jetbrains.kotlin:kotlin-test'
    // Use the Kotlin JUnit integration.
    testImplementation 'org.jetbrains.kotlin:kotlin-test-junit'
}
// Define the main class for the application.
mainClassName = 'ru.goryacms.AppKt'
2 Answers

I've tried https://github.com/reaster/schema-gen. It generates Kotlin data classes with annotations, but it has bugs so that the generated code does not compile, however this is easy to fix. In my case I also had to fix many annotations and some property names. Still much better than manually writing code.

You can try https://github.com/SixRQ/KAXB - Kotlin based class generator to generate native Kotlin classes from an XML Schema:

This project is used to generate native Kotlin classes from an xsd schema, similar to the JAXB tool for Java. The project will include a plugin for gradle and Intellij IDEA. ...

Once the archive has been extracted run the
bin/kaxb --P <destination package> --S <schema file> --T <target directory>

Related