JAXB Code Binding and Generation
We’ve said that our ultimate goal in this chapter is automated binding of XML to Java classes. Now we’ll discuss the standard Java API for XML Binding, JAXB. (This should not be confused with JAXP, the parser API.) JAXB is a standard extension that is bundled with Java 6 and later. With JAXB, the developer does not need to create any fragile parsing code. An XML schema or Java code can be used as the starting point for transforming XML to Java and back. (“Schema first” and “code first” are both supported.) With JAXB, you can either mark up your Java classes with simple annotations that map (bind) them to XML or start with an XML schema and generate plain Java classes (POJOs) with the necessary annotations included. You can even derive an XML schema from your Java classes to use as a starting point or contract with non-Java systems.
At runtime, JAXB can read an XML document and parse it into the
model that you have defined or you can go the other way, populating your
object model and then writing it out to XML. In both cases, JAXB can
validate the data to make sure it matches a schema. This may sound like
the DOM interface, but in this case we’re not using generic classes—we’re using our own model. In this
section, we’ll reuse the class model that we created for the SAX example
with our zooinventory.xml file. We’ll use the
familiar Inventory, Animal, and FoodRecipe classes directly, but this time you’ll see that we’ll be more focused on the schema ...