Learn to create XML schema document (xsd) from JAXB annotated Java classes using Eclipse IDE.
1) Add JAXB Annotations to Java Classes
First step is to add annotations such as @XmlRootElement, @XmlAccessorType and @XmlElement etc. to your Java classes.
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String firstName;
private String lastName;
private Department department;
public Employee() {
super();
}
//Setters and Getters
}
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "department")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
Integer id;
String name;
public Department() {
super();
}
//Setters and Getters
}
2) Generate XSD from JAXB Classes
2.1) Navigate to Eclipse Option
File -> New -> JAXB -> Schema from JAXB Classes

2.2) Select location for generated schema file

2.3) Select JAXB Classes

2.4) Generate xsd files
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="department" type="department"/>
<xs:element name="employee" type="employee"/>
<xs:complexType name="employee">
<xs:sequence>
<xs:element ref="department" minOccurs="0"/>
<xs:element name="firstName" type="xs:string" minOccurs="0"/>
<xs:element name="id" type="xs:int" minOccurs="0"/>
<xs:element name="lastName" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="department">
<xs:sequence>
<xs:element name="id" type="xs:int" minOccurs="0"/>
<xs:element name="name" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
XSd file has been generated and now you can use it for various application usecases.
Happy Learning !!
Comments