Although Java Architecture for XML Binding (JAXB) is fairly easy to use in nominal cases (especially since Java SE 6), it also presents numerous nuances. Some of the common nuances are due to the inability to exactlymatch (bind) XML Schema Definition (XSD) types to Java types. This post looks at one specific example of this that also demonstrates how different XSD constructs that enforce the same XML structure can lead to different Java types when the JAXB compiler generates the Java classes.
The next code listing, for
Food.xsd, defines a schema for food types. The XSD mandates that valid XML will have a root element called “Food” with three nested elements “Vegetable”, “Fruit”, and “Dessert”. Although the approach used to specify the “Vegetable” and “Dessert” elements is different than the approach used to specify the “Fruit” element, both approaches result in similar “valid XML.” The “Vegetable” and “Dessert” elements are declared directly as elements of the prescribed
simpleTypes defined later in the XSD. The “Fruit” element is defined via reference (
ref=) to another defined element that consists of a