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.
SimpleUser.java
@XmlRootElement(name="simpleUser")
public class SimpleUser {    
    protected List<SimpleAddress> addressList = new ArrayList<SimpleAddress>();
    protected String comment;
    protected int age;    
    @XmlElementWrapper(name="addresses")
    @XmlElement(name="address")
    public List<SimpleAddress> getAddressList() {
    return addressList;
    }
   ....
SimpleAddress.java
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "address",
     propOrder = {"houseNo", "society", "locality", "city", "pin","phone"})
public class SimpleAddress {    
   @XmlElement
   protected String houseNo;
   @XmlElement
   protected String society;
   @XmlElement
   protected String locality;
   @XmlElement
   protected String city;
   @XmlElement
   protected int pin;
   @XmlTransient
   protected String country;
Run the schmeagen tool on the above java classes
schemagen.sh -d .  //place where generated schema is kept
            -cp ../bin/   //classpath
             com.lalit.jaxb.SimpleUser       //list of java files          
             com.lalit.jaxb.SimpleAddress
The generates schema looks like
<?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="simpleUser" type="simpleUser"/>
  <xs:complexType name="simpleUser">
    <xs:sequence>
      <xs:element name="addresses" minOccurs="0">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="address" type="address" minOccurs="0" maxOccurs="unbounded"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="comment" type="xs:string" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="age" type="xs:int" use="required"/>
  </xs:complexType>
  <xs:complexType name="address">
    <xs:sequence>
      <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"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

More on JAXB

No comments:

Post a Comment