Newsletter sign-up
View all newsletters

Sign up for our technology specific newsletters.

Enterprise Java
Email Address:

Java-XML mapping made easy with JAXB 2.0

The new Java Architecture for XML Binding makes it easy to incorporate XML data and processing into Java applications

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

The Java Architecture for XML Binding provides a powerful and practical way of working with XML content from within Java applications. The newly released JAXB 2.0 offers many new features, including full support of all XML Schema features, significantly fewer generated classes, generated classes that are easier to manipulate, and a more flexible validation mechanism.

To understand how to process XML documents in Java with JAXB 2.0, we need to look at the two main JAXB components:

  • The binding compiler, which binds a given XML schema to a set of generated Java classes
  • The binding runtime framework, which provides unmarshalling, marshalling, and validation functionalities

The JAXB binding compiler (or xbj) lets you generate Java classes from a given XML schema. The JAXB binding compiler transforms an XML schema into a collection of Java classes that match the structure described in the XML schema. These classes are annotated with special JAXB annotations, which provide the runtime framework with the mappings it needs to process the corresponding XML documents.

The binding runtime framework provides an efficient and easy-to-use mechanism for unmarshalling (or reading) and marshalling (or writing) XML documents. It lets you transform an XML document into a hierarchy of Java objects (unmarshalling) or, inversely, transform a Java object hierarchy into XML format (marshalling). The term marshalling traditionally refers to disposing troops in some suitable manner. In networking, it refers to placing data items into a buffer before sending them over a communication channel.

Combined, these two components produce a technology that lets Java developers easily manipulate XML data in the form of Java objects, without having to know the nitty-gritty details of the Simple API for XML Processing (SAX) or the Document Object Model (DOM), or even the subtleties of XML Schema.

JAXB prerequisites

To get started with JAXB 2.0 you need:

  • Java Platform, Standard Edition 5: JAXB 2.0 relies heavily on features of Java SE 5, such as annotations and generics
  • An implementation of JAXB 2.0

This article was written using the GlassFish JAXB reference implementation release candidate.

Generate Java classes using the JAXB compiler

The JAXB compiler binds an XML schema to a set of Java classes. An XML schema is an XML document that describes, very precisely, the elements and attributes authorized in a certain type of XML document. In this example, we use a training course booking system that can accept orders in XML format. A typical order looks like this:

   <?xml version="1.0" encoding="UTF-8"?>
    <booking xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <company name="ACME Consulting">
            <address>10 Coyote Avenue,  Arizona, USA</address>
            <contact name="Duke" email="duke@acme.com" telephone="1234567890"/>
        </company>
        <student firstName="Jane" surname="Dow"/>
        <student firstName="John" surname="Doe"/>
    </booking>  


The corresponding XML schema describes how the training course is booked, and contains details of the booked course, the enrolled students, the company making the booking, and so forth. An XML schema description is extremely rigorous and can include details such as the number of elements allowed in a list of objects (cardinality), optional and mandatory attributes, and more. The schema for the training course bookings (called course-booking.xsd) is shown here:

   <?xml version="1.0" encoding="UTF-8"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <xsd:element name="booking" type="courseBooking"/>
     <xsd:complexType name="courseBooking">
      <xsd:sequence>
       <xsd:element ref="company" />
       <xsd:element ref="student"  minOccurs="1" maxOccurs="unbounded"/>
      </xsd:sequence>
      <xsd:attribute name="courseReference" type="xsd:string"  use="required"/>
      <xsd:attribute name="courseDate" type="xsd:date"  use="required"/>
      <xsd:attribute name="invoiceReference" type="xsd:string"  use="required"/>
      <xsd:attribute name="totalPrice" type="xsd:decimal"  use="required"/>
     </xsd:complexType>
     <xsd:element name="student" type="studentType"/>
     <xsd:complexType name="studentType">
       <xsd:attribute name="firstName"  type="xsd:string" use="required"/>
       <xsd:attribute name="surname" type="xsd:string" use="required"/>
     </xsd:complexType>
     <xsd:element name="company" type="companyType"/>
     <xsd:complexType name="companyType">
      <xsd:sequence>
       <xsd:element name="address"/>
       <xsd:element ref="contact" />
      </xsd:sequence>
      <xsd:attribute name="name" type="xsd:string"/>
     </xsd:complexType>
      <xsd:element name="contact" type="contactType"/>
      <xsd:complexType name="contactType">
       <xsd:attribute name="name" type="xsd:string" use="required"/>
       <xsd:attribute name="telephone" type="xsd:string" use="required"/>
       <xsd:attribute name="email" type="xsd:string" use="required"/>
     </xsd:complexType>
    </xsd:schema>   


The command line tool xjc runs the JAXB compiler. To run the JAXB compiler against our schema, we run the following command:

   $xjc course-booking.xsd -p nz.co.equinox.training.domain.booking -d src/generated  


This will generate a set of Java classes annotated with JAXB 2.0 annotations. Some of the more useful options are described here:

  • -d <dir>: Place the generated files into this directory.
  • -p <package>: Place the generated files in this package.
  • -nv: Don't perform strict validation of the input schema.
  • -httpproxy <proxy>: Use this if you are behind a proxy. Takes the format [user[:password]@]proxyHost[:proxyPort].
  • -classpath <arg>: Specify the classpath, if necessary.
  • -readOnly: Generates read-only source code files, if your OS supports this.

There is also an equivalent ant task, which makes it quite easy to integrate into an Ant or Maven-based build process.

The list of generated classes is shown here:

  CompanyType.java
   ContactType.java
   CourseBooking.java
   ObjectFactory.java
   StudentType.java


Users of previous versions of JAXB may notice that this is a slick set of annotated and fully documented Java classes, rather than the more cumbersome set of interfaces and implementations of previous versions. Thus, we have less generated classes, and lighter and more elegant code. And, as you will see in the next section, manipulating these classes is easy.

Unmarshalling an XML document

Unmarshalling is the process of converting an XML document into a corresponding set of Java objects. Unmarshalling in JAXB 2.0 is easy. First, you create a JAXBContext context object. The context object is the starting point for marshalling, unmarshalling, and validation operations. Here you specify the Java package containing your JAXB-mapped classes:

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comments (3)
Login
Forgot your account info?

UpdateBy Anonymous on July 9, 2009, 5:32 amits not working with jaxb 2.1. pls update ur code accordingly

Reply | Read entire comment

has to be. you can see that's the booking element is a Parent foBy Anonymous on May 26, 2009, 8:10 pmhas to be. you can see that's the booking element is a Parent for Student and Company.

Reply | Read entire comment

CourseBooking incomplete in example? By Anonymous on February 25, 2009, 10:33 amI'm new to JAXB and XML schema's. (Used SAX and DTD till now.) But when I look at the xsd file it seems to me that the courseReference and totalPrice attributed...

Reply | Read entire comment

View all comments

Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources