Tuesday, December 29, 2015

JAXB: Generate schema and generate Java class

You could easily generate .xsd file from java model class and vice versa.

Generate the schema

Lets have a model class as follows:

@XmlRootElement(name="product")
@XmlAccessorType(XmlAccessType.FIELD)
public class Product {

    @XmlElement(required=true) 
    protected int id;
    @XmlElement(required=true) 
    protected String name;
    @XmlElement(required=true) 
    protected String description;
    @XmlElement(required=true) 
    protected int price;
    
    public Product() {}
    
    // Getter and setter methods
    // ...
}
 
Run the JAXB schema generator on the command line to generate the corresponding XML schema definition:

schemagen Product.java

This command produces the XML schema as an .xsd file.

Generate Java class

Lets have schema definition in .xsd file:

<?xml version="1.0"?>
<xs:schema targetNamespace="http://xml.product" 
           xmlns:xs="http://www.w3.org/2001/XMLSchema"    
           elementFormDefault="qualified"
           xmlns:myco="http://xml.product">

  <xs:element name="product" type="myco:Product"/>

  <xs:complexType name="Product">
    <xs:sequence>
      <xs:element name="id" type="xs:int"/>
      <xs:element name="name" type="xs:string"/>
      <xs:element name="description" type="xs:string"/>
      <xs:element name="price" type="xs:int"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>
 
Run the schema compiler tool on the command line as follows:

xjc Product.xsd
 
This will produce the following class:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Product", propOrder = {
    "id",
    "name",
    "description",
    "price"
})
public class Product {
    protected int id;
    @XmlElement(required = true)
    protected String name;
    @XmlElement(required = true)
    protected String description;
    protected int price;

    // Setter and getter methods
    // ...
}

Source

Source: https://docs.oracle.com/javaee/6/tutorial/doc/gkknj.html

No comments:

Post a Comment