Sunday, August 17, 2014

JAXB XML to Java

JAXB also supports generating of schema from the Java code. schemagen tool helps in this. Let's write a SimpleUser and SimpleAddress class with annotation and than we can generate the schema for it.
public class SimpleUser {    
    protected List<SimpleAddress> addressList = new ArrayList<SimpleAddress>();
    protected String comment;
    protected int age;    
    public List<SimpleAddress> getAddressList() {
    return addressList;
@XmlType(name = "address",
     propOrder = {"houseNo", "society", "locality", "city", "pin","phone"})
public class SimpleAddress {    
   protected String houseNo;
   protected String society;
   protected String locality;
   protected String city;
   protected int pin;
   protected String country;
Run the schmeagen tool on the above java classes -d .  //place where generated schema is kept
            -cp ../bin/   //classpath
             com.lalit.jaxb.SimpleUser       //list of java files          
The generates schema looks like
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="">
  <xs:element name="simpleUser" type="simpleUser"/>
  <xs:complexType name="simpleUser">
      <xs:element name="addresses" minOccurs="0">
            <xs:element name="address" type="address" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element name="comment" type="xs:string" minOccurs="0"/>
    <xs:attribute name="age" type="xs:int" use="required"/>
  <xs:complexType name="address">
      <xs:element name="houseNo" type="xs:string" minOccurs="0"/>
      <xs:element name="society" type="xs:string" minOccurs="0"/>
      <xs:element name="locality" type="xs:string" minOccurs="0"/>
      <xs:element name="city" type="xs:string" minOccurs="0"/>
      <xs:element name="pin" type="xs:int"/>
      <xs:element name="phone" type="xs:string" minOccurs="0"/>

More on JAXB

No comments:

Post a Comment