Show me the code: A taste of JAXB
The following sample code is extracted from "Architecture for XML Binding (JAXB) by Ed Ort and Bhakti Mehta, March 2003" to show you a taste of how jaxb coding look like with some of my own comments pepperred in.
xjc.sh -p test.jaxb books.xsd -d work
From books.xsd generate required interfaces and implementations in a package called "test.jaxb" and place it in a directory called "work".
Convert XML to Java (Unmarshall)
//Get the context to work on
JAXBContext jc = JAXBContext.newInstance("test.jaxb");
Unmarshaller unmarshaller = jc.createUnmarshaller();
//The following is a generated test.jaxb.Collection
Collection collection= (Collection)
unmarshaller.unmarshal(new File( "books.xml"));
//Using the object
CollectionType.BooksType booksType = collection.getBooks();
List bookList = booksType.getBook();
//Write the object back to xml
Marshaller marshaller = jc.createMarshaller();
As a JAXB client there are mainly three objects. Context, marshaller, and unmarshaller. The process is quite starightforward and easy. Nevertheless obtaining the JAXBContext is quite fishy. Through out the J2EE API getting provider classes for a given API is quite inconsistent. In this case you have to pass the package names to the static function of "newInstance" to locate the provider for the "JAXBContext". Passing package names for locating implementation objects seem odd. I have read the explanations in the java api for it. I am not convinced if this is the best way to obtain an implementation for a given interface.
Convert Java to XML (Marshall)
ObjectFactory objFactory = new ObjectFactory();
//Create object shells
Collection.BooksType booksType = objFactory.
BookType book = objFactory.createBookType();
//set data items
book.setName("JAXB today and beyond");
//Validate collection (optional. If needed)
Validator validator = jaxbContext.createValidator();
//get a marshaller
Marshaller marshaller = jaxbContext.createMarshaller();
//specify output behavior
//write out xml
The interesting point to make by looking at this code is the nature in which objects are instantiated. This is done through an intermediate object factory and not by newing them. One of the reasons for this is that the implementations are not available to the developer and could be provider dependent.
Provides an executive summary, architecture, and some sample code for JAXB
This is a brief write up on on the overal state of Jaxb that I have done recently. This would be useful for Architects, Managers and decission makers.
A series of links, sample code, and articles on XML related technologies. This content is dynamic and may change as I update this folder as I find new things and organize existing items.