Wednesday, July 9, 2014

JAXB Introduction (Java Architecture for XML Binding)

What is JAXB?

JAXB, stands for Java Architecture for XML Binding, using JAXB annotation to convert Java object to / from XML file.

Why use JAXB?
  • Defines an API for reading and writing Java objects to and from XML documents.
  • Don't need to be aware of XML parsing techniques.
  • No extra dependency needed (its inside JDK)
  • Used as a standard in many cases.


 There are two operations in JAXB
  1.     Marshalling – Convert a Java object into a XML file.
  2.     Unmarshalling – Convert XML content into a Java Object. 
 Basic annotations in JAXB

@XmlRootElement

Define the root element for the XML to be produced with @XmlRootElement JAXB annotation. The name of the root XML element is derived from the class name.

@XmlRootElement
public class Country implements Serializable {
...
}


@XmlElement
 
Annotate all fields that needs to be include in XML/JSON output with @XMLElement.
@XmlElement  
  public void setCountryName(String countryName) {  
   this.countryName = countryName;  
  }
 
@XmlType
 
Specify the order in which XML elements or JSON output will be produced.
@XmlType(propOrder = { "countryName", "countryPopulation", "listOfProvince"})  
 

1 comment: