Thursday, April 14, 2011

JAXB basic example

JAXB - Java to xml binding and vice versa.

This blog is helpful for those who are new to jaxb. It just helps you to start.

1) Create java classes from xsd(if you dont have xsd use trang to generate one.). To create java classes we can use xjc.
2) Annotated java classes will be created.
3) compile the java classes.
3) Modify java classes and write marshall(Java -> xml) code inside the main method of the class.
4) Now you will get xml from the java object as part of marshalling.
for unmarshalling( xml --> Java) modify code at step3 with unmarshalling code and run the java class.
See below code for more information.

Here I am giving simple startup example on windows.

1) Download the binary and execute the jar
http://jaxb.java.net/2.2.3u2/
> java -jar JAXB2_20110412.jar
After running above command you will get a folder with name "jaxb-ri-20101209"

2) set windows classpath to C:\jaxb-ri-20101209\bin. This is to get xjc on classpath. xjc is used to generate java classes from xml.

3) Use Employee.xsd as shown below
 <?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="employee">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="firstName"/>
        <xs:element ref="middleName"/>
        <xs:element ref="lastName"/>
      </xs:sequence>
      <xs:attribute name="id" use="required" type="xs:integer"/>
    </xs:complexType>
  </xs:element>
  <xs:element name="firstName" type="xs:NCName"/>
  <xs:element name="middleName" type="xs:NCName"/>
  <xs:element name="lastName" type="xs:NCName"/>
</xs:schema>

4) run below command to genreate java classes from the xsd
     xjc Employee.xsd

5) Below Java Class will be generated
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "firstName",
    "middleName",
    "lastName"
})
@XmlRootElement(name = "employee")
public class Employee {
    @XmlElement(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NCName")
    protected String firstName;
    @XmlElement(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NCName")
    protected String middleName;
    @XmlElement(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NCName")
    protected String lastName;
    @XmlAttribute(name = "id", required = true)
    protected int id;
    /**
     * Gets the value of the firstName property.        
     */
    public String getFirstName() {
        return firstName;
    }
    /**
     * Sets the value of the firstName property.        
     */
    public void setFirstName(String value) {
        this.firstName = value;
    }
    /**
     * Gets the value of the middleName property.       
     */
    public String getMiddleName() {
        return middleName;
    }
    /**
     * Sets the value of the middleName property.    
     */
    public void setMiddleName(String value) {
        this.middleName = value;
    }
    /**
     * Gets the value of the lastName property.    
     */
    public String getLastName() {
        return lastName;
    }
    /**
     * Sets the value of the lastName property.        
     */
    public void setLastName(String value) {
        this.lastName = value;
    }
    /**
     * Gets the value of the id property.        
     */
    public int getId() {
        return id;
    }
    /**
     * Sets the value of the id property.     
     */
    public void setId(int value) {
        this.id = value;
    }
}
 
6) Add below jars to the project build path in the eclipse.
activation-1.1.jar
jaxb-api-2.0.jar
jaxb-impl-2.0.5.jar
jsr173_api-1.0.jar
jaxb-xjc.jar


7) Now modify your java class by adding main method for marshalling  i.e. java to xml.
public static void main(String args[]) throws JAXBException{
     Employee greg = new Employee();
     greg.setId(1);
     greg.setFirstName("Greg");   
     greg.setMiddleName("");
     greg.setLastName("Loyd");
   
     //java object to xml converstion    MARSHALLING
     JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
     StringWriter stringWriter = new StringWriter();
     jaxbContext.createMarshaller().marshal(greg, stringWriter);   
     System.out.println("....Marshalling....."+  stringWriter.toString());
}

8) compile above java class. You will get xml in a string fromat.

9) Modify same java class for unmarshalling.


public static void main(String args[]) throws JAXBException{
Employee greg = new Employee();
greg.setId(1);
greg.setFirstName("Greg");
greg.setMiddleName("");
greg.setLastName("Loyd");
//java object to xml converstion MARSHALLING
JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
StringWriter stringWriter = new StringWriter();
jaxbContext.createMarshaller().marshal(greg, stringWriter);
System.out.println("....Marshalling....."+ stringWriter.toString());
//End stringWriter is an xml
//xml to java object
Employee gregUnmarshal = (Employee)jaxbContext.createUnmarshaller().unmarshal(new StringReader(stringWriter.toString()));
if(greg.equals(gregUnmarshal)){
   System.out.println("....marshal and unmarshal objects are same");
}else{
   System.out.println("....marshal and unmarshal objects are not same");
}
}
package generated;

10) Run the java class and you get output for both marshalling and unmarshalling.
....Marshalling.....<?xml version="1.0" encoding="UTF-8" standalone="yes"?><employee id="1"><firstName>Greg</firstName><middleName></middleName><lastName>Loyd</lastName></employee>
....marshal and unmarshal objects are same