Download
FAQ
History
PrevHomeNext API
Search
Feedback
Divider

JAXB

The Java Architecture for XML Binding (JAXB) is a Java technology that enables you to generate Java classes from XML schemas. As part of this process, the JAXB technology also provides methods for unmarshalling an XML instance document into a content tree of Java objects, and then marshalling the content tree back into an XML document. JAXB provides a fast and convenient way to bind an XML schema to a representation in Java code, making it easy for Java developers to incorporate XML data and processing functions in Java applications without having to know much about XML itself.

One benefit of the JAXB technology is that it hides the details and gets rid of the extraneous relationships in SAX and DOM--generated JAXB classes describe only the relationships actually defined in the source schemas. The result is highly portable XML data joined with highly portable Java code that can be used to create flexible, lightweight applications and Web services.

See Chapter 10 for a description of the JAXB architecture, functions, and core concepts and then see Chapter 11, which provides sample code and step-by-step procedures for using the JAXB technology.

JAXB Binding Process

Figure 1-1 shows the JAXB data binding process.

Data Binding Process

Figure 1-1 Data Binding Process

The JAXB data binding process involves the following steps:

  1. Generate classes from a source XML schema, and then compile the generated classes.
  2. Unmarshal XML documents conforming to the schema. Unmarshalling generates a content tree of data objects instantiated from the schema-derived JAXB classes; this content tree represents the structure and content of the source XML documents.
  3. Unmarshalling optionally involves validation of the source XML documents before generating the content tree. If your application modifies the content tree, you can also use the validate operation to validate the changes before marshalling the content back to an XML document.
  4. The client application can modify the XML data represented by a content tree by means of interfaces generated by the binding compiler.
  5. The processed content tree is marshalled out to one or more XML output documents.

Validation

There are two types of validation that a JAXB client can perform:

Representing XML Content

Representing XML content as Java objects involves two kinds of mappings: binding XML names to Java identifiers, and representing XML schemas as sets of Java classes.

XML schema languages use XML names to label schema components, however this set of strings is much larger than the set of valid Java class, method, and constant identifiers. To resolve this discrepancy, the JAXB technology uses several name-mapping algorithms. Specifically, the name-mapping algorithm maps XML names to Java identifiers in a way that adheres to standard Java API design guidelines, generates identifiers that retain obvious connections to the corresponding schema, and is unlikely to result in many collisions.

Customizing JAXB Bindings

The default JAXB bindings can be overridden at a global scope or on a case-by-case basis as needed by using custom binding declarations. JAXB uses default binding rules that can be customized by means of binding declarations that can either be inlined or external to an XML Schema. Custom JAXB binding declarations also allow you to customize your generated JAXB classes beyond the XML-specific constraints in an XML schema to include Java specific refinements such as class and package name mappings.

Example

The following table illustrates some default XML Schema-to-JAXB bindings.

Table 1-1 Schema to JAXB Bindings
XML Schema
Java Class Files
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="purchaseOrder"
type="PurchaseOrderType"/>
PurchaseOrder.java
<xsd:element name="comment" type="xsd:string"/>
Comment.java
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
<xsd:element ref="comment" minOccurs="0"/>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
PurchaseOrderType.java
<xsd:complexType name="USAddress">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="street" type="xsd:string"/>
<xsd:element name="city" type="xsd:string"/>
<xsd:element name="state" type="xsd:string"/>
<xsd:element name="zip" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="country"
type="xsd:NMTOKEN" fixed="US"/>
</xsd:complexType>
USAddress.java
</xsd:schema>
 

Schema-derived Class for USAddress.java

Only a portion of the schema-derived code is shown, for brevity. The following code shows the schema-derived class for the schema's complex type USAddress.

public interface USAddress {
  String      getName();            void     setName(String);
  String      getStreet();            void     setStreet(String)  ;
  String      getCity();            void     setCity(String);
  String      getState();            void     setState(String);
  int      getZip();            void     setZip(int);
  static final String COUNTRY="USA";
}; 

Unmarshalling XML Content

To unmarshal XML content into a content tree of data objects, you first create a JAXBContext instance for handling schema-derived classes, then create an Unmarshaller instance, and then finally unmarshal the XML content. For example, if the generated classes are in a package named primer.po and the XML content is in a file named po.xml:

JAXBContext jc = JAXBContext.newInstance( "primer.po" );
Unmarshaller u = jc.createUnmarshaller();
PurchaseOrder po =
    (PurchaseOrder)u.unmarshal( new FileInputStream( "po.xml" 
) ); 

To enable unmarshal-time validation, you create the Unmarshaller instance normally, as shown above, and then enable the ValidationEventHandler:

u.setValidating( true ); 

The default configuration causes the unmarshal operation to fail upon encountering the first validation error. The default validation event handler processes a validation error, generates output to system.out, and then throws an exception:

} catch( UnmarshalException ue ) {
System.out.println( "Caught UnmarshalException" );
   } catch( JAXBException je ) {
      je.printStackTrace();
   } catch( IOException ioe ) {
      ioe.printStackTrace(); 

Modifying the Content Tree

Use the schema-derived JavaBeans component set and get methods to manipulate the data in the content tree.

USAddress address = po.getBillTo();
address.setName( "John Bob" );
address.setStreet( "242 Main Street" );
address.setCity( "Beverly Hills" );
address.setState( "CA" );
address.setZip( 90210 ); 

Validating the Content Tree

After the application modifies the content tree, it can verify that the content tree is still valid by calling the Validator.validate method on the content tree (or any subtree of it). This operation is called on-demand validation.

try{
  Validator v = jc.createValidator();
  boolean valid = v.validateRoot( po );
  ...
} catch( ValidationException ue ) {
  System.out.println( "Caught ValidationException" );
  ...
} 

Marshalling XML Content

Finally, to marshal a content tree to XML format, create a Marshaller instance, and then marshal the XML content:

Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
m.marshal( po, System.out ); 
Divider
Download
FAQ
History
PrevHomeNext API
Search
Feedback
Divider

All of the material in The Java(TM) Web Services Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.