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
// ...
}
No comments:
Post a Comment