prev table of contents next

2 Writing an XML Schema for JAXB

2.1 XML Schema Types

A schema describes data types, with the intent of defining one or more hierarchical types defining XML documents. Type information deals with the definition of structure, i.e., the composition of document nodes, and the classification of scalar (or list) values for content and attributes. The XML Schema Language offers a rich set of features to achieve the required structuring and typing. A good introduction to the XML Schema language is the XML Schema Part 0: Primer, provided by the World Wide Web Consortium (W3C).

Although all data in XML is text, it should generally not be defined as String in the Java classes derived from a schema. The XML Schema language provides the elementary data types for numbers, booleans, strings, URIs, dates and times, and for references and other XML constructs. Only by using these features will you receive the full benefit of JAXB, which will not only take care of all the necessary conversions to or from the textual representation in XML but also with the transformation of XML structures to Java data patterns, such as lists or maps.

User-defined data types can be derived from any elementary type by adding one or more restrictions. This is done by adding so-called facets, which are available to set lower or upper bounds for values or string lengths, to limit the precision, to enumerate all legal values, and to define a pattern for a string type. JAXB uses enumerations restricting strings to define an enum type. Other facets, however, are ignored by the Schmema Compiler. (Section Validation explains how to enable facet checking.)

Data structuring concepts are expressed by using the complex type construct of the schema language. An XML element of some complex type may have child elements or attributes or both. For child elements, the schema's element grouping facilites <xsd:all>, <xsd:union>, <xsd:choice> and <xsd:sequence> in combination with repetition limit attributes let you define XML structures that are the equivalent of the classic concepts of array, list, structure (or record) and union.

We'll discuss schema structuring and typing concepts in more detail in the next section, where examples of XML Schema language constructs are related to the Java code that the JAXB compiler uses for their representation.

Please notice that the tags of schema elements are presented in the qualified form, with xsd as the namespace identifier. This (or some other name, e.g., xs) identifier must be bound to the URI identifying the XML Schema language. If used, also the jxb namespace prefix must be bound. Both is done in the schema element of the XML schema:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
            jxb:version="2.0">
...


prev table of contents next