2.3 Hints on Writing XML Schemas
2.3.1 Don't Use Anonymous Types
The XML Schema language lets you define XML types anonymously. But when
you're using JAXB to generate Java classes, it's preferable to define all
schema types explicitly. For one thing, this means that you will be able to
re-use the type within your schema. More importantly, the resulting Java
class will be given the name defined in the schema rather than a name
selected by JAXB. Moreover, anonymous types result in some inner class.
Consider the following XML schema snippet:
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo" type="AddressType"/>
<xsd:element name="billTo" type="AddressType"/>
<xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="productName" type="xsd:string"/>
<xsd:element name="quantity" type="xsd:positiveInteger"/>
<xsd:element name="price" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="partNum" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
The relevant parts of the generated class PurchaseOrderType
are presented below. Note that PurchaseOrderType.Item
is
the somewhat unwieldy name of the class for an order item as it results
from an inlined schema type.
public class PurchaseOrderType {
protected AddressType shipTo;
protected AddressType billTo;
protected List<PurchaseOrderType.Item> item;
protected XMLGregorianCalendar orderDate;
// ...(getters and setters)
public List<PurchaseOrderType.Item> getItem() {
if (item == null) {
item = new ArrayList<PurchaseOrderType.Item>();
}
return this.item;
}
public static class Item {
protected String productName;
protected BigInteger quantity;
protected BigDecimal price;
protected String partNum;
// ...(getters and setters)
}
}