Skip to content

JAXB

JAXB provides an easy way to bind XML schemas to Java representations. JAXB makes it easy to incorporate XML functions into Java applications without having to know much about the particulars of XML. The binding framework facilitates the unmarshalling of XML documents into Java content trees and vice versa.

Source of Image: www.eclipse.org

Goals and Uses

  • Makes it easier to use Java applications to read, process and output XML data.
  • Provides flexible, extensible, platform-neutral formats and protocols for structuring and exchanging information.
  • Easy to access and modify XML documents within Java programs.
  • Ability to customize the binding of existing schema to Java representations
  • Portability &Provide clean “round-tripping”.
  • Access configuration values from a properties file stored in XML format.
  • Create tools to manipulate configuration properties file represented in XML format.
  • Update data received in the form of XML document without having to write SAX event handlers.

Core Components

  • XML Schema
  • Binding Declarations
  • Binding Compiler
  • Binding Framework Implementation
  • Schema-Derived Classes
  • Java Application
  • XML Input Documents (Unmarshalling)
  • XML Output Documents (Marshalling)

XML Schema

A schema is an XML specification that governs the permissible components of an XML document, and the component relationships. For example, a schema identifies the elements that may appear in an XML document, the order in which they must appear, the attributes they may have, and which elements are subordinate to other elements ( i.e., child elements). An XML document does not have to have a schema, but if it does, to be a valid XML document, it must conform to that scheme.

Binding

JAXB simplifies the access of a Java program to an XML document by presenting the XML document to the program in Java format. The first step in this process is to bind the XML document schema into a set of Java classes representing the scheme.

Binding a schema means creating a set of Java classes representing the scheme. All JAXB implementations provide a tool called a binding compiler to bind a schema (specific for implementation may be the way the binding compiler is invoked).

Unmarshalling

Unmarshalling an XML document means creating a tree of content objects representing the document's content and structure. The Tree of Content is not a tree based on DOM. In fact, content trees produced through JAXB can be more efficient than DOM-based trees in terms of memory use.

Marshalling

Marshalling is the opposite of unmarshalling. It creates an XML document out of a tree of content.

Example

you will see an example of JAXB usage in the following steps:

1. Create XML Schema demo.xsd

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Person" /> 
<xs:complexType name="Person"> 
  <xs:sequence> 
    <xs:element name="Name" type="xs:string"/> 
    <xs:element name="Address" type="Address" minOccurs="1" maxOccurs="unbounded"/> 
  </xs:sequence>
</xs:complexType> 
<xs:complexType name="Address"> 
  <xs:sequence> 
    <xs:element name="Number" type="xs:unsignedInt"/> 
    <xs:element name="Street" type="xs:string"/> 
  </xs:sequence> 
</xs:complexType>
</xs:schema>

2. Create XML Document demo.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>  
<Person>
  <Name>John Smith</Name>
  <Address> 
    <Street>ABC Street</Street> 
    <Number>5</Number> 
  </Address> 
  <Address>
    <Street>Zed Street</Street>
    <Number>168</Number>
  </Address>
</Person>  
Check that XML conforms to the Schema

3. Run the binding compiler

  • ...\jaxb\bin\xjc -p jaxb demo.xsd
    • A package named demo is created (in the directory demo)
    • The package contains (among other things):
      • interface AddressType
      • interface PersonType
public interface AddressType {
    long getNumber();
    void setNumber(long value);
    String getStreet();
    void setStreet(String value);
}
public interface PersonType {
    String getName();
    void setName(String value);
    /* List of AddressType */ 
    java.util.List getAddress();
}

4. Create Context

The context is the entry point to the API, containing methods to create Marshaller, Unmarshaller and Validator instances

JAXBContext context = JAXBContext.newInstance("demo"); 
// The package name is demo (Recall: xjc -p demo demo.xsd)

5. Unmarshal: xml to objects

Enable validation of xml according to the schema while unmarshalling:

Unmarshallerunmarshaller = context.createUnmarshaller(); 
Person person = (Person) 
  unmarshaller.unmarshal( new FileInputStream("demo.xml") );

6. Read

System.out.println("Person name=" + person.getName() ); 
Address address = (Address) person.getAddress().get(0); 
System.out.println("First Address: " + 
       " Street=" + address.getStreet() + 
       " Number=" + address.getNumber() );

7. Manipulate objects

// Update 
person.setName("Hamid Kobdani"); 
// Delete 
List addressList = person.getAddress(); 
addressList.clear();
// Create 
ObjectFactory objectFactory = new ObjectFactory(); 
Address newAddr = objectFactory.createAddressType(); 
newAddr.setStreet("Hanoter"); 
newAddr.setNumber(5); 
addressList.add( newAddr ); 

8. Validate on-demand

Validatorvalidator = context.createValidator(); 
// Check that we have set Street and Number, and that Number is non-negative 
validator.validate(newAddr); 
// Check that we have set Name, and that Address contains at least one item
validator.validate(person); 

9. Marshal: objects to xml

Marshallermarshaller = context.createMarshaller(); 
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE); 
marshaller.marshal(person, new FileOutputStream("output.xml")); 
output.xml
<Person> 
  <Name>Hamid Kobdani</Name> 
  <Address> 
    <Street>Adl Street</Street> 
    <Number>5</Number> 
  </Address> 
</Person>

Validation

Constraints

There are three categories of constraints: * Type constraints (Legal values in simple types), E.g. in every address, number is a non-negative integer * Local structural constraints, E.g. in every person, address contains at least one item * Global structural constraints, E.g. ID and IDREF

Forms

Three forms of validation * Unmarshal time validation (at unmarshal time) * On-demand validation (at any chosen point in time) * validateRoot(object) vs. validate(object) * validateRoot includes global constraint checking * Fail-fast validation (at all times) * Currently not implemented * Checks that the value provided to a set method is legal

When validation errors occur an event is raised (no exception) and validation continues, so that several validation errors can be handled. Default handler raises an exception on first error.

Exercise

Exercise 1: generate code for demo.xsd using xjc: * xjc -p jaxb demo.xsd:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Person" /> 
<xs:complexType name="Person"> 
  <xs:sequence> 
    <xs:element name="Name" type="xs:string"/> 
    <xs:element name="Address" type="Address" 
           minOccurs="1" maxOccurs="unbounded"/> 
  </xs:sequence>
</xs:complexType> 
<xs:complexType name="Address"> 
  <xs:sequence> 
    <xs:element name="Number" type="xs:unsignedInt"/> 
    <xs:element name="Street" type="xs:string"/> 
  </xs:sequence> 
</xs:complexType>
</xs:schema>

  • Exercise 2:
    • write an unmarshaller for the following XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>  
<PersonType>
  <Name>John Smith</Name>
  <AddressType> 
    <Street>ABC Street</Street> 
    <Number>5</Number> 
  </AddressType> 
  <AddressType>
    <Street>Zed Street</Street>
    <Number>168</Number>
  </AddressType>
</PersonType>