Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

Generating Java classes from an XSD is a common use case. I am partial to the Highsource (e.g. jvnet) maven-jaxb2-plugin. This plugin is very easy to use. Add the following to your pom.xml.

<build>
    <plugins>
        <plugin>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId>
            <version>0.13.2</version>
            <executions>
                <execution>
                    <id>generate</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

By default, the plugin will compile any xsd files located in src/main/resources. They will be generated in target/generated-sources/xjc/generated.

Generated Classes

By default, the generated classes will be in the generated package. To customize this value, include an XJB file in the same directory as the target XSD. I prefer to do one XJB for each XSD like the following.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings
        version="2.1"
        xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
        xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <jaxb:bindings schemaLocation="a.xsd" node="//xs:schema">
        <jaxb:schemaBindings>
            <jaxb:package name="org.ab.a"/>
        </jaxb:schemaBindings>
    </jaxb:bindings>
</jaxb:bindings>

September 12th, 2017

Posted In: Javaninja

Leave a Reply

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

LinkedIn Auto Publish Powered By : XYZScripts.com