In this howto I will show you how to create a XML Schema from an annotated JAXB class using the maven jaxb-schemagen plugin.
STEP 1: Annotate your domain classes with JAXB annotations.
In our example we have a simple Contact class with name, surname, birthday and a list of mails.
@XmlRootElement public class Contact { private String name; private String surname; private Birthday birthday; private List<Mail> mail; // Add getters & setters }
And the Birthday class:
@XmlType public class Birthday { private String day; private String month; private String year; // Add getters & setters }
And the Mail class:
@XmlType public class Mail { public enum MailType { PERSONAL, WORK }; private String email; private MailType type; // Add getters & setters }
STEP 2: Annotate the XML namespace as a package annotation
The package-info.java
@XmlSchema ( xmlns = {}, namespace = "http://www.jordeu.net/XSDCREATOR/1.0.0", elementFormDefault = XmlNsForm.UNSET, attributeFormDefault = XmlNsForm.UNSET ) package net.jordeu.codesnips.xsdcreator; import javax.xml.bind.annotation.XmlSchema; import javax.xml.bind.annotation.XmlNsForm;
STEP 3: Config Maven pom.xml
First add this repository to the pom.xml or check that you have it in your settings.xml or proxy repository.
<pluginRepository> <id>maven-repository.dev.java.net</id> <name>Java.net Maven 2 Repository</name> <url>http://download.java.net/maven/2</url> </pluginRepository>
And add this plugin changing the “includes” section and “schemas” section according to your project name and layout.
<plugin> <groupId>com.sun.tools.jxc.maven2</groupId> <artifactId>maven-jaxb-schemagen-plugin</artifactId> <version>1.2</version> <executions> <execution> <phase>generate-resources</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <project>${project}</project> <destdir>${project.build.directory}/schemas</destdir> <srcdir>${project.build.sourceDirectory}</srcdir> <includes> <include>net/jordeu/codesnips/xsdcreator/*</include> </includes> <schemas> <schema> <namespace>http://www.jordeu.net/XSDCREATOR/1.0.0</namespace> <file>xsdcreator-v1_0_0.xsd</file> </schema> </schemas> <verbose>true</verbose> </configuration> <dependencies> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-xjc</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-xjc</artifactId> <version>2.2</version> </dependency> </dependencies> </plugin>
Checkout the sample project
at https://github.com/jordeu/codesnips