Tutorial

How to generate XSD from Java Class

Published on August 3, 2022
author

Pankaj

How to generate XSD from Java Class

In last few posts, we learned about Java JAXB and how to generate java class from XSD. Today we will learn how to generate XSD from java classes.

Generate XSD from Java Class

generate xsd from java, xsd generator, java class to xsd We will use JAXB-2 Maven Plugin in a maven project to generate XSD from java classes.

  • JAXB2 Maven Plugin uses JAXB SchemaGenerator utility to generate XSD from java classes.
  • Java classes should have JAXB annotations to be used by this plugin.
  • Minimum java version required is Java 5

First create a new maven project, you can give any name, group id and artifact id you want. Once we will build our project, it will generate XSD classes in target/generated-resources/schemagen directory. After build, our project structure will look like below image. generate xsd from java class example Here is the final pom.xml file we have:

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>jaxb-schemagen</groupId>
	<artifactId>jaxb-schemagen</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<version>2.1</version>
		</dependency>
	</dependencies>

	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>2.5.1</version>
				</plugin>
			</plugins>
		</pluginManagement>

		<plugins>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>jaxb2-maven-plugin</artifactId>
				<version>1.5</version>
				<executions>
					<execution>
						<id>schemagen</id>
						<goals>
							<goal>schemagen</goal>
						</goals>
					</execution>
				</executions>

				<configuration>
					<transformSchemas>
						<transformSchema>
							<uri>https://www.example.org/employee</uri>
							<toPrefix>empns</toPrefix>
							<toFile>employee.xsd</toFile>
						</transformSchema>
						<transformSchema>
							<uri>https://www.example.org/address</uri>
							<toPrefix>addrns</toPrefix>
							<toFile>address.xsd</toFile>
						</transformSchema>
					</transformSchemas>
					<includes>
						<include>com/journaldev/bean/*</include>
					</includes>
					<verbose>true</verbose>

				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Few things to notice are jaxb dependency, schemagen execution goal and transformSchema configuration. transformSchema configuration is used to specify the XSD file name generated and namespace prefix to be used in the XSD file. Here are the java classes we have that will be used to generate XSD. Employee.java

package com.journaldev.bean;


import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

@XmlType(namespace = "https://www.example.org/employee")
public class Employee {
    private String name;
    private int id;
    private String role;
    private Address address;


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    @XmlAttribute
    public int getId() {
        return id;
    }


    public void setId(int id) {
        this.id = id;
    }


    public String getRole() {
        return role;
    }


    public void setRole(String role) {
        this.role = role;
    }


    public Address getAddress() {
        return address;
    }


    public void setAddress(Address address) {
        this.address = address;
    }
}

Notice the XmlType annotation with namespace used for the class and XmlAttribute for the field id. This class will generate employee.xsd schema once we build the project. As you can see that it has a field Address that is another custom class, so we need to annotate this class also for successful schema generation. Here is the address class with jaxb annotations. Address.java

package com.journaldev.bean;

import javax.xml.bind.annotation.XmlType;

@XmlType(namespace = "https://www.example.org/address")
public class Address {
    private String city;
    private int zip;
    private String addressLine1;
    private String addressLine2;
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public int getZip() {
        return zip;
    }
    public void setZip(int zip) {
        this.zip = zip;
    }
    public String getAddressLine1() {
        return addressLine1;
    }
    public void setAddressLine1(String addressLine1) {
        this.addressLine1 = addressLine1;
    }
    public String getAddressLine2() {
        return addressLine2;
    }
    public void setAddressLine2(String addressLine2) {
        this.addressLine2 = addressLine2;
    }
    
}

This class will generate address.xsd because it’s name is matched in transformSchema in pom.xml file. Our project setup is ready, just build the project using command mvn clean install and the XSD files will be generated. For my project, generated XSD files are as below. employee.xsd

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema xmlns:xs="https://www.w3.org/2001/XMLSchema" xmlns:addrns="https://www.example.org/address" targetNamespace="https://www.example.org/employee" version="1.0">

  <xs:import namespace="https://www.example.org/address" schemaLocation="address.xsd"/>

  <xs:complexType name="employee">
    <xs:sequence>
      <xs:element minOccurs="0" name="address" type="ns1:address"/>
      <xs:element minOccurs="0" name="name" type="xs:string"/>
      <xs:element minOccurs="0" name="role" type="xs:string"/>
    </xs:sequence>
    <xs:attribute name="id" type="xs:int" use="required"/>
  </xs:complexType>
</xs:schema>

address.xsd

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema xmlns:xs="https://www.w3.org/2001/XMLSchema" targetNamespace="https://www.example.org/address" version="1.0">

  <xs:complexType name="address">
    <xs:sequence>
      <xs:element minOccurs="0" name="addressLine1" type="xs:string"/>
      <xs:element minOccurs="0" name="addressLine2" type="xs:string"/>
      <xs:element minOccurs="0" name="city" type="xs:string"/>
      <xs:element name="zip" type="xs:int"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

That’s all for generating XSD from java class. It’s very simple and great way for java class to XSD generation. I hope you will find it useful and easy to understand.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 15, 2018

Where can I see generated XSD file?

- AMITKUMAR PATEL

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 23, 2017

    Thank you Sir, It’s a good tutorial. where I can download your jaxb-schemmagen Thanks

    - Pham

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 11, 2015

      Thank you very much.

      - Ahmet

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 21, 2013

        Hi, good morning, I did as told, however it seems that the schemagen maven plugin creates the folder with the schema, but not only that, it generates the compiled classes. Would you know what’s is going on and how to solve it? (I mean, generate only the XSD files.) Thanks, Miguel

        - Miguel Garz

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          May 10, 2013

          In your example, employee.xsd at line #8 reads “ns1:address”, whereas should be “addrns:address”. By the way, this is only one of jaxb2-maven-plugin issues. The other problem is that it (when using “schemagen” goal) also unnecessarily generates additional compiled classes in the schema output directory, which is strange (and they can accidentally end up in your jar in addition to original oxm-annotaded classes but in a different package…). Trying make this plugin work w/o issues either way have never been a success, and I finally gave up using transformSchemas, XmlType with xmlns declarations, and non-default output directory with this plugin altogether…

          - IR

            Try DigitalOcean for free

            Click below to sign up and get $200 of credit to try our products over 60 days!

            Sign up

            Join the Tech Talk
            Success! Thank you! Please check your email for further details.

            Please complete your information!

            Featured on Community

            Get our biweekly newsletter

            Sign up for Infrastructure as a Newsletter.

            Hollie's Hub for Good

            Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

            Become a contributor

            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

            Welcome to the developer cloud

            DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

            Learn more