1. The JAXB stands for “Java Architecture for XML Binding“.
  2. The JAXB standardizes serialization i.e.,we do not have to define the XML to which their Java classes are mapped rather a default type mapping is provided by the JAXB.
  3. JAXB provides type mapping from Java Types to XML Types(and vice versa).
  4. The (de)serializers are used to implement type mappings.Hence,JAXB standardizes Java/XML or XML/Java binding.
  5. The JAXB has standard rules for (de)serializing XML schema components to/from Java objects i.e., JAXB provides a solid framework for Java/XML binding.
  6. The JAXB maps Java class definition to XML Schema definition as well as maps Java object to XML message.

JAXB Architecture

JAXB

Start from Java

The Java classes exist first and are used to generate XML schema using JAXB 2.0 schema generator(schemagen) tool.This tool is part of J2SE 1.6 or JWSDP 2.0 or J2EE 1.5

Start from XML Schema

The schema(s) exist first and the Java classes are generated using JAXB 2.0 schema compiler(xjc) tool.This tool is part of J2SE 1.6 or WSDP 2.0 or J2EE 1.5

Binding runtime framework

Provides Marshalling to convert Java object into XML message at runtime.
Also, provides Unmarshalling to convert XML message into Java object at runtime.

JAXB Binding process

An XML schema is used as input to JAXB binding compiler(xjc) tool to generate JAXB classes.
The Java classes are used as input to the JAXB schema generator (schemagen) tool to generate XML Schema.

The unmarshaller creates Java Objects from XML Document.
The marshaller creates XML Document from Java object.
MarshalUnmarshal

The JAXB binding can be:

  1. Standard JAXB Binding(annotations are implied)
  2. Customize JAXB Binding(Specify annotations explicitly)

Standard JAXB Binding

  1. The schema compiler(or schema generator) tools does the mapping automatically for us i.e.,JAXB defines defaults to supply implied annotations wherever needed.
  2. JAXB defines a standard mapping from XML Schema to Java class(and vice versa) that relives programmers of the tedious work related to define their own mappings.

#simpleorder.xsd

<schema targetNamespace="http://www.example.com/oms"
 elementFormDefault="qualified"
 xmlns="http://www.w3.org/2001/XMLSchema"
 xmlns:tns="http://www.example.com/oms">

<!--Top level element-->
<element name="simpleOrder">
<!--anonymous complex type -->
<complexType>
   <sequence>
      <element name="bilTo">
            <!--anonymous complex type -->
        <complexType>
            <sequence>
                 <element name="name" type="string"/>
                 <element name="street" type="string"/>
                 <element name="city" type="string"/>
                 <element name="state" type="string"/>
                 <element name="zip" type="string"/>
                 <element name="phone" type="string"/>
           </sequence>   
       </complexType>
     </element>

    <element name="items">
        <!--anonymous complex type-->
      <complexType>
        <sequence>
          <element name="item" type="tns:ItemType" maxOccurs="unbounded"/>
       </sequence>
     </complexType>
   </element>
 </sequence>
</complexType>
</element>

<!--named complexType-->
 <complexType name="ItemType">
    <sequence>
        <element name="quantity" type="positiveInteger"/>
        <element name="price" type="double"/>
    </sequence>
    <attribute name="productName" use="required" type="string"/>
 </complexType>
</schema>

The standard binding does following:

  1. By default,the target namespace http://www.example.com/oms gets mapped with the java package com.example.oms.If we want a different package name,we can add the <jaxb:package> binding language annotation to .xsd or the @XmlSchema(namespace) annotation to existing java class
  2. The top level element always mapped with top level class whose name is same as element name.
  3. The named complexType always mapped with top level class whose name is same as name of the complex type.
  4. By default,the sub elements with anonymous complextype mapped with static inner classes.We can force all classes to be generated as top-level by adding the <jaxb:globalBindings localScoping=”toplevel”/> binding annotation.
  5. Each sub element becomes a property of top level class.Hence,the <billTo>and <items> sub elements becomes billTo,items properties of a class
  6. When an element sets maxOccurs value greater than 1,then by default,it maps with List<T>.The collection type can be customized using the binding language element <jaxb:property>with ‘collectionType’ attribute globally or locally
  7. The default mapping for xs:positiveInteger is java.math.BigInteger.This mapping can be customized using the binding language <jaxb:JavaType> declaration or the “@XmlElement(type) annotation.
  8. The attribute maps with a property with JavaBean style setter/getter methods.

Use schema compiler(xjc) tool to generate JAXB java classes.
xjc

SimpleOrder.java

package com.example.oms;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "bilTo",
    "items"
})
@XmlRootElement(name = "simpleOrder")
public class SimpleOrder {

    @XmlElement(required = true)
    protected SimpleOrder.BilTo bilTo;
    @XmlElement(required = true)
    protected SimpleOrder.Items items;

    
    public SimpleOrder.BilTo getBilTo() {
        return bilTo;
    }

    public void setBilTo(SimpleOrder.BilTo value) {
        this.bilTo = value;
    }

    
    public SimpleOrder.Items getItems() {
        return items;
    }

    
    public void setItems(SimpleOrder.Items value) {
        this.items = value;
    }

	@XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "name",
        "street",
        "city",
        "state",
        "zip",
        "phone"
    })
    public static class BilTo {

        @XmlElement(required = true)
        protected String name;
        @XmlElement(required = true)
        protected String street;
        @XmlElement(required = true)
        protected String city;
        @XmlElement(required = true)
        protected String state;
        @XmlElement(required = true)
        protected String zip;
        @XmlElement(required = true)
        protected String phone;

        //setter and getter methods

    }

	@XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "item"
    })
    public static class Items {

        @XmlElement(required = true)
        protected List<ItemType> item;

        public List<ItemType> getItem() {
            if (item == null) {
                item = new ArrayList<ItemType>();
            }
            return this.item;
        }

    }

}


ItemType.java

package com.example.oms;

import java.math.BigInteger;
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.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ItemType", propOrder = {
    "quantity",
    "price"
})
public class ItemType {

    @XmlElement(required = true)
    protected BigInteger quantity;
    protected double price;
    @XmlAttribute(required = true)
    protected String productName;

    public BigInteger getQuantity() {
        return quantity;
    }

  
    public void setQuantity(BigInteger value) {
        this.quantity = value;
    }
   
    public double getPrice() {
        return price;
    }
   
    public void setPrice(double value) {
        this.price = value;
    }
  
    public String getProductName() {
        return productName;
    }
    public void setProductName(String value) {
        this.productName = value;
    }

}

The above annotations are automatically added by schema compiler(‘xjc’) tool.These annotations are used by marsheller and unmarsheller at runtime.

The following table describes jaxb annotations which were automatically added in generated java classes:

Annotation Purpose Example
@XmlAccessorType Tells the JAXB runtime binding which part of the java class gets mapped by default. /the possible values are:
XmlAccessType.FIELD
XmlAccessType.PROPERTY
XmlAccessType.NONE
XmlAccessType.PUBLIC_MEMBER
Note:XmlAccessType.PUBLIC_MEMBER is the default value.
@XmlType Map class to XML type(complexType) The ‘name’ attribute specifies name of the complexType.If ‘name’ is set as “” then it is anonymous type.
The ‘propOrder’ attribute is equivalent to <sequence>.
The ‘namespace’ attribute specifies targetNameSpace.
@XmlRootElement Specifies top level element name. The ‘name’ attribute specifies top level element name.
The ‘namespace’ attribute specifies targetNameSpace.
@XmlElement The field or property maps to xml element The ‘name’ attribute specifies sub element name.
The ‘namespace’ attribute specifies targetNameSpace.
The ‘required’ attribute indicates the element optional or mandatory.
@XmlAttribute Indicates the field or property maps to attribute The ‘required’ attribute indicates the attribute is mandatory

The annotations are the key to run-time marshalling and unmarshalling while converting Java Objects with XML Message (and vice versa).
By default,JAXB does not validate against schema, rather it delegates such validations to JAXP 1.3 API.We can activate such validations
by using the setSchema(javax.xml.validation.Schema schema) method on either Marshaller or Unmarshaller instance.

Example:

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.StringReader;
import java.math.BigInteger;
import java.util.List;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import com.example.oms.ItemType;
import com.example.oms.SimpleOrder;
import com.example.oms.SimpleOrder.BilTo;
import com.example.oms.SimpleOrder.Items;
public class StandardSerializer{
  public static void main(String[] args){
  
	SimpleOrder order=new SimpleOrder();
	BilTo billTo = new BilTo();
		billTo.setName("John Doe");
		billTo.setStreet("125 Main Street");
		billTo.setCity("Any Town");
		billTo.setState("NM");
		billTo.setZip("95811");
		billTo.setPhone("(831) 874-1123");

	    ItemType it1 = new ItemType();
		it1.setProductName("Diet Coke");
		it1.setQuantity(new BigInteger("6"));
		it1.setPrice((float) 2.99);

		ItemType it2 = new ItemType();
		it2.setProductName("Potato Chips");
		it2.setQuantity(new BigInteger("4"));
		it2.setPrice((float) 3.99);

		Items items = new Items();
		List<ItemType> itemTypes = items.getItem();
		itemTypes.add(it1);
		itemTypes.add(it2);

		order.setBilTo(billTo);
		order.setItems(items);
	try{
		JAXBContext jaxbContext=JAXBContext.newInstance(SimpleOrder.class);
		Marshaller jaxbMarshaller=jaxbContext.createMarshaller();
		jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
					Boolean.TRUE);
			SchemaFactory sf = SchemaFactory
					.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
			//The below two lines are required only if we want to validate xml message againg xsd using jaxp1.3
			//Schema schema = sf.newSchema(new File("simpleorder.xsd"));
			//jaxbMarshaller.setSchema(schema);
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		jaxbMarshaller.marshal(order, baos);//Generates XML Message
		System.out.println(baos.toString());
		
		Unmarshaller u=jaxbContext.createUnmarshaller();
		SimpleOrder roundTripOrder=(SimpleOrder)u.unmarshal(new StringReader(baos.toString()));
		System.out.println("phone="+roundTripOrder.getBilTo().getPhone());
		
	}catch(Exception ex){
		ex.printStackTrace();
	}
  
  }

}


Output:

StandardSerializer

Download Project StandardSerializer

Customize JAXB Binding

The annotations allows customization of standard JAXB binding.
We can customize Java/XML or XML/Java binding based on application specific requirement.

  1. Write Custom Java code(mapping code) to map from an existing java POJOs to a JAXB2.0 generated java classes, and then use JAXB2.0 marshalling to create the XML instance.
  2. Add JAXB2.0 annotations to existing POJOs.
  3. Add JAXB2.0 binding language annotations to existing schema.
  4. Use the JAXB2.0 XmlAdapter class to implement custom marshalling from an existing Java class to an existing XML Schema.
Type Mapping with JAXB2.0 Annotations
  1. The JAXB2.0 annotations are used to customize the JAXB2.0 standard mappings.
  2. We can add annotations to existing POJOs so that they directly map with target schema.
  3. the JAXB2.0 runtime binding directly marshal/unmarshal our annotated POJOs to XML documents.
  4. the following existing POJOs(but not generated JAXB java classes) are added with annotations manually.
  5. The explicit annotations are not needed when the JAXB standard default mapping does the job
  6. .

#MySimpleOder.java

package samples;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="simpleOrder")
public class MySimpleOrder {

  private MyAddress billTo;
  private List<MyItem> itemList;

  // must add a no-arg constructor
  public MySimpleOrder() {}
    
  public MySimpleOrder(String name, String street, String city, String state,
      String zip, String phone) {
    this(new MyAddress(name, street, city, state, zip, phone));
  }
  
  public MySimpleOrder(MyAddress addr) {
    this.billTo = addr;
    itemList = new ArrayList<MyItem>();
  }

  public MyAddress getBillTo() {
    return billTo;
  }
  
  public void setBillTo(MyAddress billTo) {
    this.billTo = billTo;
  }

  @XmlElementWrapper(name="items")
  @XmlElement(name="item")
  public List<MyItem> getItemList() {
    return itemList;
  }
  
  public void setItemList(List<MyItem> itemList) {
    this.itemList = itemList;
  }
}

#MyAddress.java

package samples;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", 
    propOrder = {"name", "street", "city", "state", "zip", "phone"})
public class MyAddress {
 //properties
  protected String name;
  protected String street;
  protected String city;
  protected String state;
  protected String zip;
  protected String phone;

  // need a no-arg constructor
  public MyAddress() {};

  
  public MyAddress(String name, String street, String city, String state,
      String zip, String phone) {

    this.name = name;
    this.street = street;
    this.city = city;
    this.state = state;
    this.zip = zip;
    this.phone = phone;
    
  }
  
}

#MyType.java

package samples;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

@XmlType(name = "ItemType", propOrder = {"quantity", "price"})
public class MyItem {
  //properties
  private int quantity;
  private float price;
  private String productName;

  // need a no-arg constructor
  public MyItem() {};
  
  public MyItem(int quantity, float price, String productName) 
  throws Exception {
    if (productName == null) {
      throw new Exception("productName cannot be null");
    }
      this.productName = productName;
      this.price = price;
      this.quantity = quantity;
  }

  public float getPrice() {
    return price;
  }

  public void setPrice(float price) {
    this.price = price;
  }

  @XmlAttribute
  public String getProductName() {
    return productName;
  }

  public void setProductName(String productName) {
    this.productName = productName;
  }

  public int getQuantity() {
    return quantity;
  }

  public void setQuantity(int quantity) {
    this.quantity = quantity;
  }

}

The @xmlRootElement(name=”simpleOrder”)annotation maps to top level whose name is same as value of the ‘name‘ attribute.If the ‘name‘ attribute is not specified then the class name becomes element name .If the ‘namespace‘ attribute is not specified,the top level element namespace is derived from the package name.In this case the package name is samples,so the default namespace would br http://samples.However,JAXB provides a mechanism to specify a global mapping for the package using package-info.java file.

Example:

@XmlSchema(namespace=”http://www.example.com/oms”,elementFormDefault=XmlNsForm.QUALIFIED)
package samples;

The @XmlAccssorType annotation does not appear in this case,hence JAXB binding uses standard value which is @XmlAccsorType(XmlAccessType.PUBLIC_MEMBER).It indicates that every public getter/setter pair and every public field will be automatically bound to XML unless annotated by XmlTrasient.

The @XmlType annotations does not appear in this case,hence JAXB binding uses standard mapping which is @XmlType(name=” <class name >”)

Use schema generator(schemagen) tool to generate XSD.
schemagen

Generated xsd.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema elementFormDefault="qualified" version="1.0" targetNamespace="http://www.example.com/oms" xmlns:tns="http://www.example.com/oms" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="simpleOrder" type="tns:mySimpleOrder"/>

  <xs:complexType name="mySimpleOrder">
    <xs:sequence>
      <xs:element name="billTo" minOccurs="0">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="name" type="xs:string" minOccurs="0"/>
            <xs:element name="street" type="xs:string" minOccurs="0"/>
            <xs:element name="city" type="xs:string" minOccurs="0"/>
            <xs:element name="state" type="xs:string" minOccurs="0"/>
            <xs:element name="zip" type="xs:string" minOccurs="0"/>
            <xs:element name="phone" type="xs:string" minOccurs="0"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="items" minOccurs="0">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="item" type="tns:ItemType" maxOccurs="unbounded" minOccurs="0"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="ItemType">
    <xs:sequence>
      <xs:element name="quantity" type="xs:int"/>
      <xs:element name="price" type="xs:float"/>
    </xs:sequence>
    <xs:attribute name="productName" type="xs:string"/>
  </xs:complexType>
</xs:schema>

#MySimpleOrderSerializer.java

import samples.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.StringReader;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

public class MySimpleOrderSerializer {

  public static void main(String[] args) throws Exception {
    
    MySimpleOrder myOrder = new MySimpleOrder(
        "John Doe",
        "125 Main Street",
        "Any Town", "NM", "95811",
        "(831) 874-1123");
    myOrder.getItemList().add(new MyItem(6, (float) 2.99, "Diet Coke"));
    myOrder.getItemList().add(new MyItem(4, (float) 3.99, "Potato Chips"));
    myOrder.getItemList().add(new MyItem(2, (float) 5.34, "Frozen Pizza"));
    try {
      JAXBContext jaxbContext = JAXBContext.newInstance(MySimpleOrder.class);
      Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, 
          Boolean.TRUE);
      SchemaFactory sf = 
        SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      //Schema schema = sf.newSchema(new File("samples/schema1.xsd"));
      //jaxbMarshaller.setSchema(schema);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      jaxbMarshaller.marshal(myOrder, baos);
      System.out.println(baos.toString());
      /*Unmarshaller u = jaxbContext.createUnmarshaller();
      MySimpleOrder roundTripOrder = 
        (MySimpleOrder) u.unmarshal(new StringReader(baos.toString()));
      System.out.println("phone = " + roundTripOrder.getBillTo().phone);*/
      
    } catch (Exception e) {
      e.printStackTrace();
    } 
  }
}

Output:
MySimpleOrder

Download Project:
JAXBAnnotation
Drawbacks

  1. Annotating POJOs requires access to the source code
  2. Many type mappings cannot be implemented using annotations.

solutions

  1. Write Custom Mapping Code
  2. JAXB 2.0 Customization Framework(i.e.,the@XmlJavaTypeAdaptor annotation)
  3. Wrapper classes(used situations where we don’t want to or cannot annotate POJOs)
  4. The SOA-J framework avoids wrapper classes

TypeMappings with the JAXB 2.0 Binding Language

  1. The Binding Languageannotations used to customize existing XML Schema i.e.,add binding language declarations to the existing XML Schema.
  2. The Schema Compiler interprets and uses to generate annotated Java classes.Such annotted java classes are used by marshaling and unmarshalling processes.


Example:
simpleorder_bindinglang.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema targetNamespace="http://www.example.com/oms"
  elementFormDefault="qualified" xmlns="http://www.w3.org/2001/XMLSchema"
  xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="2.0"
  xmlns:oms="http://www.example.com/oms">
  <annotation>
    <appinfo>
      <jaxb:globalBindings localScoping="toplevel"/>
      <jaxb:schemaBindings>
        <jaxb:package name="samples"/>
      </jaxb:schemaBindings>
    </appinfo>
  </annotation>
 
  <element name="simpleOrder">
    <annotation>
      <appinfo>
        <jaxb:class name="MySimpleOrder"/>
      </appinfo>
    </annotation>
    <complexType>
      <sequence>
        <element name="billTo">
          <complexType>
            <annotation>
              <appinfo>
                <jaxb:class name="MyAddress"/>
              </appinfo>
            </annotation>
            <sequence>
              <element name="name" type="string"/>
              <element name="street" type="string"/>
              <element name="city" type="string"/>
              <element name="state" type="string"/>
              <element name="zip" type="string"/>
              <element name="phone" type="string"/>
            </sequence>
          </complexType>
        </element>
   
        <element name="items">
          <complexType>
            <sequence>
              <element name="item" type="oms:ItemType" maxOccurs="unbounded"/>
            </sequence>
          </complexType>
        </element>
      </sequence>
    </complexType>
  </element>

  <complexType name="ItemType">
    <annotation>
      <appinfo>
        <jaxb:class name="MyItem"/>
      </appinfo>
    </annotation>
    <sequence>
      <element name="quantity" type="positiveInteger">
        <annotation>
          <appinfo>
            <jaxb:property>
              <jaxb:baseType>
                <jaxb:javaType name="int"
                  parseMethod="javax.xml.bind.DatatypeConverter.parseInt"
                  printMethod="javax.xml.bind.DatatypeConverter.printInt"/>
              </jaxb:baseType>
            </jaxb:property>
          </appinfo>
        </annotation>
      </element>
      <element name="price" type="double">
        <annotation>
          <appinfo>
            <jaxb:property>
              <jaxb:baseType>
                <jaxb:javaType name="float"
                  parseMethod="javax.xml.bind.DatatypeConverter.parseFloat"
                  printMethod="javax.xml.bind.DatatypeConverter.printFloat"/>
              </jaxb:baseType>
            </jaxb:property>
          </appinfo>
        </annotation>
      </element>
    </sequence>
    <attribute name="productName" use="required" type="string"/>
  </complexType>
</schema>

Generating java classes

xjc_binding

#MySimpleOrderSerializer.java

import samples.*;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.math.BigInteger;
import java.net.URL;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import samples.MySimpleOrder;

public class MySimpleOrderSerializer {
  public static void main(String[] args) throws Exception {
    
    MySimpleOrder myOrder = new MySimpleOrder();
    myOrder.setBillTo(new MyAddress());
    myOrder.getBillTo().setName("John Doe");
    myOrder.getBillTo().setStreet("125 Main Street");
    myOrder.getBillTo().setCity("Any Town");
    myOrder.getBillTo().setState("NM");
    myOrder.getBillTo().setZip("95811");
    myOrder.getBillTo().setPhone("(831) 874-1123");
    Items items = new Items();
    myOrder.setItems(items);
    List<MyItem> itemList = items.getItem();
    MyItem myItem = new MyItem();
    myItem.setPrice((float) 2.99);
    myItem.setQuantity(6);
    myItem.setProductName("Diet Coke");
    itemList.add(myItem);
    myItem = new MyItem();
    myItem.setPrice((float) 3.99);
    myItem.setQuantity(4);
    myItem.setProductName("Potato Chips");
    itemList.add(myItem);
    myItem = new MyItem();
    myItem.setPrice((float) 5.34);
    myItem.setQuantity(2);
    myItem.setProductName("Frozen Pizza");
    itemList.add(myItem);
    try {
      JAXBContext jaxbContext = JAXBContext.newInstance(MySimpleOrder.class);
      Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, 
          Boolean.TRUE);
      SchemaFactory sf = 
        SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      ByteArrayOutputStream ba = new ByteArrayOutputStream();
      jaxbMarshaller.marshal(myOrder, ba);
      System.out.println(ba.toString());
     } catch (Exception e) {
      e.printStackTrace();
    } 
  }
}

Output:
output

download Project: BindingLanguage

JAXB Features
jaxb provides many features,they area:
1.Type mapping[XML Types/Java types and vice versa]
2.Annotations
3.Binding Language
4.portability

JAXB runtime binding uses annotations to determine how to marshal/unmarshal java objects to XML Messages and vice cersa.