Sun Java Solaris Communities My SDN Account Join SDN
 
Article

Architecture for XML Binding (JAXB): A Primer

 
 

Articles Index

.
. . .
.

Note: This article discusses an early access version of JAXB that worked exclusively with DTD schema, differing significantly from the final JAXB v1.0 specification. Please check out http://java.sun.com/webservices/jaxb for the latest on JAXB technology.

.
.
.

This article introduces you to the basics of Java Architecture for XML Binding (JAXB) Early Access Implementation v 1.0. You will learn a few basic uses of the API and tools that the EA v 1.0 provides. This paper provides brief explanations on how to create simple binding codes using the API and tools. In addition, this paper also discusses a few situations where JAXB shows its strengths, and is intended for developers who have working understanding of the Java programming language, are familiar with XML, and interested in getting a brief introduction to JAXB.

Introduction to JAXB

Java Architecture for XML Binding (JAXB) provides an API and tool that allow automatic two-way mapping between XML documents and Java objects. With a given Document Type Definition (DTD) and a schema definition, the JAXB compiler can generate a set of Java classes that allow developers to build applications that can read, manipulate and recreate XML documents without writing any logic to process XML elements. The generated codes provide an abstraction layer by exposing a public interface that allows access to the XML data without any specific knowledge about the underlying data structure. In addition to DTD support, future versions of JAXB will add support for other schema languages, such as the W3C XML Schema. These features enable the JAXB to provide many benefits for the developers, which are further explained in the next section.

A Few Benefits of JAXB

The immediate advantage of JAXB is that it provides a layer of abstraction that enables developers to quickly and conveniently work with XML documents. This advantage is made possible with

  • Valid Data: A JAXB application follows the definition of DTD and schema strictly, which does not permit the creation of invalid Java data objects.
  • Speed: SAX (Simple API for XML) is fast with its event-driven model that parses data as a stream, and a JAXB application can match the speed with its binding mechanism.
  • Ease of Use: The JAXB compiler generates the processing codes, which frees developers from manually writing and debugging conversion codes. With generated conversion codes, developers can write applications that access XML data through Java interfaces and do not need to worry about the structure of data.
  • Data Conversion: Data in XML documents can be converted to Java data types.
  • Customization: Binding schema can be customized for different needs.
  • Extensibility: The generated classes can be extended to provide additional functionality.

For further explanations, please see the Java Architecture for XML Binding User's Guide.

Uses of JAXB

An application can take advantage of the benefits that JAXB can offer if a developer wants to do the following:

  • Manipulate data in memory.
  • Work with valid data that conforms with DTD and binding schema.
  • Generate processing codes based on a DTD.
  • Work with Java objects that represent XML data.
  • Read and write XML documents using generated processing codes.
  • Access data from multiple XML documents.

Developers may discover additional uses of JAXB, and ways to benefit from its features. There are also situations where a different XML processing API may provide additional advantages, such as Java API for XML Processing (JAXP). JAXP provides a SAX parser API, a Document Object Model (DOM) parser API, and an XSL Transformations API. For further information about JAXP API, please refer to the links at the bottom of this document. In the following situations, JAXP can provide these options for developers:

  • Use SAX API if the application only needs a piece of data from a large XML document.
  • DOM API can be used if an XML document is not too large and data manipulation is needed.
  • Transformation from one XML document to another.
  • Customize processing code to handle not well defined DTDs and/or invalid XML files.
  • Parse XML documents based on different DTDs using the same processing code.

Different features that JAXB and JAXP offer can empower developers to have the option to choose the best API to fit their needs. If the decision is to use JAXB, then the following step-by-step instruction will provide a jump start on the basics of using the JAXB API.

Getting Started

Before starting to work with the JAXB API, it will need to be downloaded and installed. An implementation can be downloaded from the official JAXB page. Once the package is installed, developers will be able to try out the following simple price list example that shows the basics of using the JAXB API. In this example, a list of product names and prices for each product are tracked in XML, which may look like Code Sample 1. JAXB applications implemented to process this XML document can provide additional business logic to satisfy desired functionality.

Code Sample 1: Sample XML for the price list example

<item_list>
     <item_info>
     <name>Pen</name>
     <price>1.99</price>
     </item_info>
</item_list>

To build a simple JAXB application to process the above sample XML file, the following steps are used to provide an overview of the development process:

  1. Create or obtain a DTD
  2. Define a binding schema
  3. Generate processing codes
  4. Unmarshal from an XML document
  5. Instantiation
  6. Work with data
  7. Validation
  8. Marshal to an XML document

Create or Obtain a DTD

In order to generate XML processing codes, the JAXB compiler requires a DTD, which defines simple constraints on structure and contents of a XML document. To keep this example simple, the DTD will define an item_list that can have zero or many (denoted by "*") item_info elements, which have a name and price. Both name and price elements contain data (denoted by "#PCDATA") that is going to be parsed by parsing code generated by the JAXB tool. See Code Sample 2 for the DTD of the price list example.

Code Sample 2: A simple DTD for item list example: item.dtd

<!ELEMENT item_list (item_info*)>
<!ELEMENT item_info (name, price)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT price(#PCDATA)>

Define a Binding Schema

See Code Sample 3 for a minimal binding schema that binds item_list as the root of the XML document and leaves all data to the default binding, which is String type. Note that both item_list and item_info are bound as class type and will be the class names of the generated Java source code.

Code Sample 3: A minimal binding schema: item.xjs

<xml-java-binding-schema> 
     <element name="item_list" type="class" root="true"/>
     <element name="item_info" type="class"/>
</xml-java-binding-schema>

Generate Processing Codes

Assuming that the JAXB EA Implementation v 1.0 is installed and set up correctly, run the following command in a command prompt or terminal to generate the processing codes:

xjc item.dtd item.xjs

Please note that xjc is the schema compiler that is part of the JAXB distribution. The parameters specified are files that are shown in Code Samples 2 and 3.

Unmarshal from an XML Document

Unmarshaling is the process of populating a JAXB generated class object with a corresponding XML document. To unmarshal a XML document, call the unmarshal method in a JAXB generated class object with a parameter of InputStream type that contains contents of a corresponding XML document. The code fragment below shows how to unmarshal XML from a file.

File file = new File("itemList.xml"); 
ItemList il = new  ItemList(); 
try{ 
    FileInputStream fin = new FileInputStream(file); 
    il = il.unmarshal(fin); 
}finally{ 
    fin.close(); 
}

Instantiation

If there is no existing XML document to work with or a new XML document is needed, a new instance of item_list object can be created following the following three general steps:

  1. Create new instances of objects.
  2.     ItemList il = new ItemList();
        ItemInfo ii = new ItemInfo();
    
  3. Use the set methods to initialize the data.
    Simple strings are passed as parameters directly, since all of the data members uses the default binding, which is String type.
  4.     ii.setName("Pen");
        ii.setPrice("1.99");
    
  5. Add ItemInfo to ItemList.
    To add an item_info object into an item_list, call getContent method to get a reference to a List object, which allows manipulation of the list data in item_list.
  6.     List l = il.getContent();
        l.add(ii);
    

If the ItemInfo object contains another list, just reapply the same tricks by calling the getContent method on the ItemInfo object and add the appropriate object(s) to the list prior to adding it to ItemList. To keep this example simple, only one list is used.

Work with Data

In addition to the steps described in the previous section to create new instances of JAXB generated classes, there are also other get methods available to retrieve data. In this example, the get methods are getName and getPrice.

Validation

Validation is the process of verifying that the Java object representation of a XML document conforms with the DTD. Validation is required prior to marshaling if content has been added or modified on the Java object representation. To validate the content, just call the validate method similar to the sample code fragment below:

il.validate();

Marshal to a XML document

Marshaling is the process of producing an XML document from Java objects. Marshaling the contents object to a XML document follows a similar process to unmarshaling. The marshal method takes an OutputStream object as the parameter. In this case, FileOutputStream is used to write the XML content into a file with the name itemList2.xml.

File outFile = new File("itemList2.xml"); 
try{ 
    FileOutputStream fout = new FileOutputStream(outFile); 
    il. marshal(fout); 
}finally { 
    fout.close(); 
}

Summary

This paper provided a brief overview of the JAXB API. Within this overview, a short list of benefits described the many advantages of using JAXB API, provided an explanation on the use of JAXB, and when an alternative API should be used. To show how a simple JAXB application uses the API, the second half of this paper presented a simple example walkthrough that showed the basics of using the API.

By now you should have a basic understanding of the JAXB API and tools in the EA v. 1.0 distribution. With this understanding, you can start writing simple applications that take advantages of the many features and advantages offered by the JAXB. Fore more complex processing techniques, please read the Java Architecture for XML Binding User's Guide.

Further Readings and References

JAXB

JAXP

DTD