Specification: Jakarta XML Binding Version: 4.0 Status: Final Release Release: February 21, 2022
Copyright (c) 2019, 2022 Eclipse Foundation.
Eclipse Foundation Specification License
By using and/or copying this document, or the Eclipse Foundation document from which this statement is linked, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions:
Permission to copy, and distribute the contents of this document, or the Eclipse Foundation document from which this statement is linked, in any medium for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the document, or portions thereof, that you use:
-
link or URL to the original Eclipse Foundation document.
-
All existing copyright notices, or if one does not exist, a notice (hypertext is preferred, but a textual representation is permitted) of the form: "Copyright (c) [$date-of-document] Eclipse Foundation, Inc. [url to this license]"
Inclusion of the full text of this NOTICE must be provided. We request that authorship attribution be provided in any software, documents, or other items or products that you create pursuant to the implementation of the contents of this document, or any portion thereof.
No right to create modifications or derivatives of Eclipse Foundation documents is granted pursuant to this license, except anyone may prepare and distribute derivative works and portions of this document in software that implements the specification, in supporting materials accompanying such software, and in documentation of such software, PROVIDED that all such works include the notice below. HOWEVER, the publication of derivative works of this document for use as a technical specification is expressly prohibited.
The notice is:
"Copyright (c) 2018 Eclipse Foundation. This software or document includes material copied from or derived from [title and URI of the Eclipse Foundation specification document]."
Disclaimers
THIS DOCUMENT IS PROVIDED "AS IS," AND THE COPYRIGHT HOLDERS AND THE ECLIPSE FOUNDATION MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; THAT THE CONTENTS OF THE DOCUMENT ARE SUITABLE FOR ANY PURPOSE; NOR THAT THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
THE COPYRIGHT HOLDERS AND THE ECLIPSE FOUNDATION WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE DOCUMENT OR THE PERFORMANCE OR IMPLEMENTATION OF THE CONTENTS THEREOF.
The name and trademarks of the copyright holders or the Eclipse Foundation may NOT be used in advertising or publicity pertaining to this document or its contents without specific, written prior permission. Title to copyright in this document will at all times remain with copyright holders.
Scope
The Jakarta XML Binding provides an API and tools that automate the mapping between XML documents and Java objects.
1. Introduction
XML is, essentially, a platform-independent means of structuring information. An XML document is a tree of elements . An element may have a set of attributes , in the form of key-value pairs, and may contain other elements, text, or a mixture thereof. An element may refer to other elements via identifier attributes or other types via type attributes, thereby allowing arbitrary graph structures to be represented.
An XML document need not follow any rules beyond the well-formedness criteria laid out in the XML 1.0 specification. To exchange documents in a meaningful way, however, requires that their structure and content be described and constrained so that the various parties involved will interpret them correctly and consistently. This can be accomplished through the use of a schema . A schema contains a set of rules that constrains the structure and content of a document’s components, i.e. , its elements, attributes, and text. A schema also describes, at least informally and often implicitly, the intended conceptual meaning of a document’s components. A schema is, in other words, a specification of the syntax and semantics of a (potentially infinite) set of XML documents. A document is said to be valid with respect to a schema if, and only if, it satisfies the constraints specified in the schema.
In what language is a schema defined? The XML specification itself describes a sublanguage for writing document-type definitions , or DTDs. As schemas go, however, DTDs are fairly weak. They support the definition of simple constraints on structure and content, but provide no real facility for expressing datatypes or complex structural relationships. They have also prompted the creation of more sophisticated schema languages such as XDR, SOX, RELAX, TREX, and, most significantly, the XML Schema language defined by the World Wide Web Consortium. The XML Schema language has gained widespread acceptance. It is the schema language of choice for many of the XML related specifications authored by industry standard working groups.
Therefore, the design center for this specification is W3C XML Schema language.
1.1. Data binding
Any nontrivial application of XML will, then, be based upon one or more schemas and will involve one or more programs that create, consume, and manipulate documents whose syntax and semantics are governed by those schemas. While it is certainly possible to write such programs using the low-level SAX parser API or the somewhat higher-level DOM parse-tree API, doing so is not easy. The resulting code is also difficult to maintain as the schemas evolve. While useful to some, many applications access and manipulate XML content within a document; its document structure is less relevant.
It would be much easier to write XML-enabled programs if we could simply map the components of an XML document to in-memory objects that represent, in an obvious and useful way, the document’s intended meaning according to its schema. Of what classes should these objects be instances? In some cases there will be an obvious mapping from schema components to existing classes, especially for common types such as String, Date, Vector, and so forth. In general, however, classes specific to the schema being used will be required.
Classes specific to a schema may be derived or may already exist. In some application scenarios e.g. web services, a data model composed using user authored classes may already exist. A schema is derived from existing classes. In-memory objects are instances of existing classes. In other application scenarios, a data model is composed by authoring a schema. In such cases, rather than burden developers with having to write classes specific to schema, we can generate the classes directly from the schema. In all application scenarios, we create a Java object-level binding of the schema.
But even applications manipulating documents at conceptual object level, may desire to access or manipulate structural information in a document, e.g. element names. Therefore, the ability for an application to relate between the XML document representation and the Java object-level binding enables the use of XML operations over the XML document representation, e.g. Xpath.to bind XML content to an object model such as DOM is useful.
An XML data-binding facility therefore contains a schema compiler and a schema generator. A schema compiler can consume a schema and generate schema derived classes specific to the schema. A schema generator consumes a set of existing classes and generates a schema.
A schema compiler binds components of a
source schema to schema-derived Java value classes. Each value class
provides access to the content of the corresponding schema component via
a set of JavaBeans-style access (i.e., get
and set
) methods.
Binding declarations provides a capability to customize the binding
from schema components to Java representation.
A schema generator binds existing classes to
schema components. Each class containing Java Beans-style access
(i.e., get
and set
) methods is bound to a corresponding schema
component. Program annotations provide a capability to customize the
binding from existing classes to derived schema components.
Access to content is through in-memory representation of existing classes.
Such a facility also provides a binding framework , a runtime API that, in conjunction with the derived or existing classes, supports three primary operations:
-
The unmarshalling of an XML document into a tree of interrelated instances of both existing and schema-derived classes,
-
The marshalling of such content trees back into XML documents, and
-
The binding, maintained by a binder, between an XML document representation and content tree.
The unmarshalling process has the capability
to check incoming XML documents for validity with respect to the
schema.
To sum up: Schemas describe the structure and meaning of an XML document, in much the same way that a class describes an object in a program. To work with an XML document in a program we would like to map its components directly to a set of objects that reflect the document’s meaning according to its schema. We can achieve this by compiling the schema into a set of derived content classes or by compiling a set of existing classes into a schema and marshalling, unmarshalling and validating XML documents that follow the schema. Data binding thus allows XML-enabled programs to be written at the same conceptual level as the documents they manipulate, rather than at the more primitive level of parser events or parse trees.
Schema evolution in response to changing application requirements, is inevitable. A document therefore might not always necessarily follow the complete schema, rather a part of a versioned schema. Dealing with schema evolution requires both a versioning strategy as well as more flexible marshalling, unmarshalling and validation operations.
XML applications, such as workflow applications, consist of distributed, cooperative components interoperating using XML documents for data exchange. Each distributed component may need to access and update only a part of the XML document relevant to itself, while retaining the fidelity of the rest of the XML document. This is also more robust in the face of schema evolution, since the changes in schema may not impact the part of the document relevant to the application. The binder enables partial binding of the relevant parts of the XML document to a content tree and marshalling updates back to the original XML document.
1.2. Goals
The Jakarta XML Binding architecture is designed with the goals outlined here in mind.
-
Full W3C XML Schema support
Support for XML Schema features not required to be supported in JAXB 1.0 has been added in this version. -
Binding existing Java classes to generated XML schema
This addresses application scenarios where design begins with Java classes rather than an XML schema. One such example is an application that exports itself as a web service that communicates using SOAP and XML as a transport mechanism. The marshalling of Java object graph is according to program annotations, either explicit or defaulted, on the existing Java classes. -
Meet data binding requirements for Jakarta XML Web Services
Jakarta XML Web Services will use the XML data binding facility defined by Jakarta XML Binding. Hence, Jakarta XML Binding will meet all data binding requirements of Jakarta XML Web Services. -
Ease of Development: Leverage J2SE 5.0 Language Extensions
For ease of development, J2SE 5.0 introduces additional language language extensions.The language extensions include generics (JSR 14), typesafe enums (JSR201), annotations (JSR 175). Use of the language extensions in binding of XML schema components to Java representation will result in a better and simpler binding, thus making the application development easier. -
Container Managed Environments
A container managed environment separates development from the deployment phases. This enables choice of generation of artifacts such as derived classes or derived schema at either development or deployment time. Any requirements related to the deployment of components using Jakarta XML Binding in a container managed environment will be addressed. -
Schema evolution
Schema evolution is a complex and difficult area; it is also an important area. It is particularly important in data centric applications such as Web services, where distributed applications interact using XML as a data interchange format but are designed with different versions of the schema. It is also important in document centric applications where schemas are designed for extensibility. Strategies to address both application scenarios will be investigated and support added accordingly. -
Application specific behavior
There should be a way to associate application specific behavior with schema derived code in a portable manner. -
Partial mapping of XML document relevant to application
In some application scenarios, only a subset of the data within a XML document may be relevant to the application. -
Integration with other Java technologies
Integration or relationship with the following Java technologies will be clarified.-
Streaming API For XML (JSR 173) (StAX)
-
-
Relationship to XML related specifications
XML related specifications will be surveyed to determine their relationship to Jakarta XML Binding. -
Portability of Jakarta XML Binding mapped classes
An architecture that provides for a fully portable Jakarta XML Binding applications written to the Java SE platform will be defined.
Jakarta XML Binding annotated classes must be source level and binary compatible with any other Jakarta XML Binding binding framework implementation. Schema-derived interfaces/implementation classes are only required to be source code compatible with other Jakarta XML Binding implementations of the same version. -
Preserving equivalence - Round tripping (Java to XML to Java)
Transforming a Java content tree to XML content and back to Java content again should result in an equivalent Java content tree before and after the transformation. -
Preserving equivalence - Round tripping (XML to Java to XML)
While JAXB 1.0 specification did not require the preservation of the XML information set when round tripping from XML document to Java representation and back to XML document again, it did not forbid the preservation either. The same applies to Jakarta XML Binding specification. -
Unmarshalling invalid XML content
Unmarshalling of invalid content was out of scope for JAXB 1.0. Simple binding rules and unmarshalling mechanisms that specify the handling of invalid content will be defined. -
Ease of Use - Manipulation of XML documents in Java
Lower the barrier to entry to manipulating XML documents within Java programs. Programmers should be able to access and modify XML documents via a Java binding of the data, not via SAX or DOM. It should be possible for a developer who knows little about XML to compile a simple schema and immediately start making use of the classes that are produced.
Rather than not supporting XML Schema extensibility concepts that can not be statically bound, such as unconstrained wildcard content, these concepts should be exposed directly as DOM or some other XML infoset preserving representation since there is no other satisfactory static Java binding representation for them. -
Customization
Applications sometimes require customization to meet their data binding requirements. Customization support will include:-
XML to Java:
A standard way to customize the binding of existing XML schema components to Java representation will be provided. JAXB 1.0 provided customization mechanisms for the subset of XML Schema components supported in JAXB 1.0. Customization support will be extended to additional XML Schema features to be supported in this version of the specification, see Full W3C XML Schema support. -
Java to XML:
A standard way to customize the binding of existing Java classes to XML schema will be added, see Binding existing Java classes to generated XML schema.
-
-
Schema derived classes should be natural
Insofar as possible, derived classes should observe standard Java API design guidelines and naming conventions. If new conventions are required then they should mesh well with existing conventions. A developer should not be astonished when trying to use a derived class. -
Schema derived classes should match conceptual level of source schema
It should be straightforward to examine any content-bearing component of the source schema and identify the corresponding Java language construct in the derived classes.
1.3. Non-Goals
-
Support for Java versions prior to J2SE 5.0
Jakarta XML Binding relies on many of the Java language features added in J2SE 5.0. It is not a goal to support Jakarta XML Binding on Java versions prior to J2SE 5.0. -
Explicit support for specifying the binding of DTD to a Java representation.
While it was desired to explicitly support binding DTD to a Java representation, it became impractical to describe both XML Schema binding and DTD binding. The existence of several conversion tools that automate the conversion of a DTD to XML Schema allows DTD users to be able to take advantage of Jakarta XML Binding technology by converting their existing DTDs to XML Schema. -
XML Schema Extensions
XML Schema specification allows the annotation of schemas and schema components with appinfo elements. JAXB 1.0 specifies the use of appinfo elements to customize the generated code. For Jakarta XML Binding specification, use of appinfo elements for customization of generated code continues to be in scope. However, use of appinfo element to introduce validation constraints beyond those already described in XML Schema 1.0 specification is out of scope. -
Support for SOAP Encoding
SOAP Encoding is out of scope. Use of the SOAP encoding is essentially deprecated in the web services community, e.g. the WS-I Basic Profile[WSIBP] excludes SOAP encoding. -
Support for validation on demand by schema derived classes
While working with a content tree corresponding to an XML document it is often necessary to validate the tree against the constraints in the source schema. It is a non goal in Jakarta XML Binding specification, which leverages the JAXP validation API, to make the validation possible to do at any time, without the user having to first marshal the tree into XML. -
Object graph traversal
Portable mechanisms to traverse a graph of JavaBean objects will not be addressed in Jakarta XML Binding specification. -
Mapping any existing Java classes to any existing XML schema
The Jakarta XML Binding annotation mechanism is not sophisticated enough to enable mapping an arbitrary class to all XML schema concepts.
1.4. Conventions
Within normative prose in this specification, the words should and must are defined as follows:
-
should
Conforming implementations are permitted to but need not behave as described. -
must
Conforming implementations are required to behave as described; otherwise they are in error.
Throughout the document, references to JAXB refer to the Jakarta XML Binding
unless otherwise noted. The XML namespace
prefix xs:
and xsd:
refers to schema components in W3C XML Schema
namespace as specified in [XSD Part 1] and [XSD Part 2]. The XML
namespace prefix xsi:
refers to the XML instance namespace defined in
[XSD Part 1]. Additionally, the XML namespace prefix jaxb:
refers to
the Jakarta XML Binding namespace, https://jakarta.ee/xml/ns/jaxb
. The XML
namespace prefix ref:
refers to the namespace
http://ws-i.org/profiles/basic/1.1/xsd
as defined in [WSIBP] and
[WSIAP].
All examples in the specification are for illustrative purposes to assist in understanding concepts and are non-normative. If an example conflicts with the normative prose, the normative prose always takes precedence over the example.
1.5. Expert Group Members
The following people have contributed to this specification.
Chavdar Baikov |
SAP AG |
David Bau |
|
Arnaud Blandin |
|
Stephen Brodsky |
IBM |
Russell Butek |
IBM |
Jongjin Choi |
TMAX |
Glen Daniels |
Sonic Software |
Blaise Doughan |
Oracle |
Christopher Fry |
BEA Systems |
Stanley Guan |
Oracle |
Mette Hedin |
|
Kohsuke Kawaguchi |
Sun Microsystems, Inc. |
Sravan Kumar |
Pramati Technologies |
Changshin Lee |
Tmax Soft, Inc. |
Anjana Manian |
Oracle |
Ed Merks |
IBM |
Steve Perry |
Fidelity Information Services |
Radu Preotiuc-Pietro |
BEA |
Srividya Rajagopalan |
Nokia Corporation |
Yann Raoul |
|
Bjarne Rasmussen |
Novell, Inc. |
Adinarayana Sakala |
IONA Technologies PLC |
Dennis M. Sosnoski |
|
Keith Visco |
|
Stefan Wachter |
|
Umit Yalcinalp |
|
Scott Ziegler |
BEA Systems |
Zulfi Umrani |
Novell, Inc. |
1.6. Acknowledgements
This document is a derivative work of concepts and an initial draft initially led by Mark Reinhold of Sun Microsystems. Our thanks to all who were involved in pioneering that initial effort. The feedback from the Java User community on the initial Jakarta XML Binding technology prototype greatly assisted in identifying requirements and directions.
The data binding experiences of the expert group members have been instrumental in identifying the proper blend of the countless data binding techniques that we have considered in the course of writing this specification. We thank them for their contributions and their review feedback.
Kohsuke Kawaguchi and Ryan Shoemaker have directly contributed content to the specification and wrote the companion javadoc. The following Jakarta XML Binding technology team members have been invaluable in keeping the specification effort on the right track: Tom Amiro, Leonid Arbouzov, Evgueni Astigueevitch, Jennifer Ball, Carla Carlson, Patrick Curran, Scott Fordin, Omar Fung, Peter Kacandes, Dmitry Khukhro, Tom Kincaid, K. Ari Krupnikov, Ramesh Mandava, Bhakti Mehta, Ed Mooney, Ilya Neverov, Oleg Oleinik, Brian Ogata, Vivek Pandey, Cecilia Peltier, Evgueni Rouban and Leslie Schwenk. The following people, all from Sun Microsystems, have provided valuable input to this effort: Roberto Chinnici, Chris Ferris, Mark Hapner, Eve Maler, Farrukh Najmi, Eduardo Pelegri-llopart, Bill Shannon and Rahul Sharma.
The Jakarta XML Binding TCK software team would like to acknowledge that the NIST XML Schema test suite [NIST] has greatly assisted the conformance testing of this specification.
1.7. Acknowledgements for Jakarta XML Binding
Original version of this specification was created under the Java Community Process as JSR-222. This specification is shaped by valuable input from expert group members, people with Sun, and Java User community feedback based on their experience with JAXB 1.0.
The data binding experience of the expert group has been very instrumental in identifying usage scenarios (including those from web services),design and evaluation of different databinding techniques. We thank them for their contributions and review feedback.
The following people, all from Sun Microsystems, have provided valuable input. The experiences of the reference implementation team, led by Kohsuke Kawaguchi, has been influential in identifying data binding solutions. Kohsuke Kawaguchi and Ryan Shoemaker have directly contributed content to the companion javadoc.Addtional feedback was provided by the following JAXB technology team members: Bhakti Mehta, Ed Mooney, Ryan Shoemaker, Karthikeyan Krishnamurthy, Tom Amiro, Leonid Arbouzov, Leonid Kuskov, Dmitry Fazunenko, Dmitry Lepekhin, Alexey Vishentsev, Omar Fung, and Anita Jindal. Valuable input was provided by the following people from Sun: Eduardo Pelegri-Llopart, Graham Hamilton, Mark Hapner, Bill Shannon.
The Jakarta XML Binding TCK software team would like to acknowledge that the NIST XML Schema test suite [NIST] has greatly assisted the conformance testing of this specification.
2. Requirements
This chapter specifies the scope and requirements for this version of the specification.
2.1. XML Schema to Java
2.1.1. W3C XML Schema support
The mapping of the following XML Schema components must be specified.
-
type substitution ( @xsi:type )
-
element substitution group ( <xs:element @substitutionGroup >)
-
wildcard support( xs:any and xs:anyAttribute )
-
identity constraints ( xs:key , xs:keyref and xs:unique )
-
redefinition of declaration ( xs:redefine )
-
NOTATION
For binding builtin XML Schema datatypes which do not map naturally to Java datatypes, Java datatypes specified by JAXP 1.3 (JSR 206) must be used.
2.1.2. Default Bindings
There must be a detailed, unambiguous description of the default mapping of schema components to Java representations in order to satisfy the portability goal.
2.1.3. Customized Binding Schema
A binding schema language and its formats must be specified. There must be a means to describe the binding without requiring modification to the original schema. Additionally, the same XML Schema language must be used for the two different mechanisms for expressing a binding declaration.
2.1.4. Overriding default binding behavior
Given the diverse styles that can be used to design a schema, it is daunting to identify a single ideal default binding solution. For situations where several equally good binding alternatives exist, the specification will describe the alternatives and select one to be the default (see Customized Binding Schema).
The binding schema must provide a means to specify an alternative binding for the scope of an entire schema. This mechanism ensures that if the default binding is not sufficient, it can easily be overridden in a portable manner.
2.1.5. Jakarta XML Web Services
2.1.5.1. Backward Compatibility
Mapping of XML Schema to schema derived Java classes as specified in versions of Jakarta XML-RPC either by default or by customization is out of scope.
2.1.5.2. Binding XML Schema to schema derived classes
A binding of XML Schema constructs to schema derived classes must be specified.
2.1.5.3. Accessing MIME content stored as an attachment
The W3C XMLP MTOM/XOP document and WS-I AP 1.0[WSIAP] both provide mechanisms for embedding references to SOAP attachments in SOAP messages. It is desirable to bind these to suitable Java types (e.g. Image or DataHandler) rather than just provide URI refs.
2.1.5.4. Serializable
A customization must be specified to enable
schema derived classes to implement the java.io.Serializable
interface. This capability enables the schema derived instance to be
passed as EJB method parameter and to any other API that requires
Serializable instances.
2.1.5.5. Disabling Databinding
A customization to disable databinding must be specified. When databinding is disabled, an XML Schema component is bound to an XML fragment representation rather than a strongly typed datatype determined by mapping rules. Binding to XML fragment allows the use of alternative binding technologies for example to perform XML operations.
2.2. Java to XML Schema
2.2.1. Default Mapping
A default mapping Java constructs to XML Schema must be specified. The default mapping may be overridden by customizations described in Customized Mapping.
2.2.2. Customized Mapping
A customization mechanism to override default mapping of Java constructs to XML Schema constructs must be specified. Since XML Schema provides a much richer feature set than Java language for defining data models, the scope of customizations will be restricted to enable mapping to commonly used XML Schema constructs.
Support for the following mechanism must be specified:
-
customization mechanism using the JSR175 program annotation facility.
2.2.3. Jakarta XML Web Services
2.2.3.1. WSDL <types>
The WSDL <types> is generated using Java constructs to XML Schema mapping. The latter should therefore define customizations that enable mapping to XML Schema constructs commonly used in web services, subject to the requirements in Customized Mapping and Default Mapping.
2.3. Binding Framework
2.3.1. Disabling schema validation
The specification will provide an ability to disable schema validation for unmarshal and marshal operations.
There exist a significant number of scenarios that do not require validation and/or can not afford the overhead of schema validation. An application must be allowed to disable schema validation checking during unmarshal and marshal operations. The goal of this requirement is to provide the same flexibility and functionality that a SAX or DOM parser allows for.
3. Architecture
3.1. Introduction
This chapter describes the architectural components, comprising the XML-databinding facility, that realize the goals outlined in Goals. The scope of this version of specification covers many additional goals beyond those in JAXB 1.0. As a result, JAXB 1.0 architecture has been revised significantly.
3.2. Overview
The XML data-binding facility consists of the following architectural components:
-
schema compiler: A schema compiler binds a source schema to a set of schema derived program elements. The binding is described by an XML-based language, binding language.
-
schema generator: A schema generator maps a set of existing program elements to a derived schema. The mapping is described by program annotations.
-
binding runtime framework that provides two primary operations for accessing, manipulating and validating XML content using either schema derived or existing program elements:
-
Unmarshalling is the process of reading an XML document and constructing a tree of content objects. Each content object is an instance of either a schema derived or an existing program element mapped by the schema generator and corresponds to an instance in the XML document. Thus, the content tree reflects the document’s content.
Validation can optionally be enabled as part of the unmarshalling process. Validation is the process of verifying that an xml document meets all the constraints expressed in the schema. -
Marshalling is the inverse of unmarshalling, i.e., it is the process of traversing a content tree and writing an XML document that reflects the tree’s content. Validation can optionally be enabled as part of the marshalling process.
-
As used in this specification, the term schema includes the W3C XML Schema as defined in the XML Schema 1.0 Recommendation[XSD Part 1][XSD Part 2]. Non-Normative Jakarta XML Binding Architecture diagram illustrates relationships between concepts introduced in this section.
JAXB-annotated classes are common to both binding schemes. They are either generated by a schema compiler or the result of a programmer adding JAXB annotations to existing Java classes. The universal unmarshal/marshal process is driven by the JAXB annotations on the portable JAXB-annotated classes.
Note that the binding declarations object in the above diagram is logical. Binding declarations can either be inlined within the schema or they can appear in an external binding file that is associated with the source schema.
Note that the application accesses only the
schema-derived interfaces, factory methods and jakarta.xml.bind
APIs
directly. This convention is necessary to enable switching between JAXB
implementations.
3.3. Java Representation
The content tree contains instances of bound types, types that bind and provide access to XML content. Each bound type corresponds to one or more schema components. As much as possible, for type safety and ease of use, a bound type that constrains the values to match the schema constraints of the schema components. The different bound types, which may be either schema derived or authored by a user, are described below.
Value Class A coarse grained schema component, such as a complex type definition, is bound to a Value class. The Java class hierarchy is used to preserve XML Schema’s “derived by extension” type definition hierarchy. JAXB-annotated classes are portable and in comparison to schema derived interfaces/implementation classes, result in a smaller number of classes.
Property A fine-grained schema component, such as an attribute declaration or an element declaration with a simple type, is bound directly to a property or a field within a value class.
A property is realized in a value class by
a set of JavaBeans-style access methods. These methods include the
usual get
and set
methods for retrieving and modifying a property’s
value; they also provide for the deletion and, if appropriate, the
re-initialization of a property’s value.
Properties are also used for references from one content instance to another. If an instance of a schema component X can occur within, or be referenced from, an instance of some other component Y then the content class derived from Y will define a property that can contain instances of X.
Binding a fine-grained schema component to a field is useful when a bound type does not follow the JavaBeans patterns. It makes it possible to map such types to a schema without the need to refactor them.
Interface JAXB 1.0 bound schema components (XML content) to schema derived content interfaces and implementation classes. The interface/implementation classes tightly couple the schema derived implementation classes to the Jakarta XML Binding implementation runtime framework and are thus not portable. The binding of schema components to schema derived interfaces continues to be supported in Jakarta XML Binding.
Note
The mapping of existing Java interfaces to schema constructs is not supported. Since an existing class can implement multiple interfaces, there is no obvious mapping of existing interfaces to XML schema constructs. |
Enum type J2SE 5.0 platform introduced linguistic support for type safe enumeration types. Enum type are used to represent values of schema types with enumeration values.
Collection type Collections are used to represent content models. Where possible, for type safety, parametric lists are used for homogeneous collections. For e.g. a repeating element in content model is bound to a parametric list.
DOM node In some cases, binding XML content to a DOM or DOM like representation rather than a collection of types is more natural to a programmer. One example is an open content model that allows elements whose types are not statically constrained by the schema.
Content tree can be created by unmarshalling of an XML document or by programmatic construction. Each bound type in the content tree is created as follows:
-
schema derived implementation classes that implement schema derived interfaces can be created using factory methods generated by the schema compiler.
-
schema derived value classes can be created using a constructor or a factory method generated by the schema compiler.
-
existing types, authored by users, are required to provide a no arg constructor. The no arg constructor is used by an unmarshaller during unmarshalling to create an instance of the type.
3.3.1. Binding Declarations
A particular binding of a given source schema
is defined by a set of binding declarations . Binding declarations are
written in a binding language , which is itself an application of XML.
A binding declaration can occur within the annotation appinfo
of each
XML Schema component. Alternatively, binding declarations can occur in
an auxiliary file. Each binding declaration within the auxiliary file is
associated to a schema component in the source schema. It was necessary
to support binding declarations external to the source schema in order
to allow for customization of an XML Schemas that one prefers not to
modify. The schema compiler hence actually requires two inputs, a source
schema and a set of binding declarations.
Binding declarations enable one to override default binding rules, thereby allowing for user customization of the schema-derived value class. Additionally, binding declarations allow for further refinements to be introduced into the binding to Java representation that could not be derived from the schema alone.
The binding declarations need not define every last detail of a binding. The schema compiler assumes default binding declarations for those components of the source schema that are not mentioned explicitly by binding declarations. Default declarations both reduce the verbosity of the customization and make it more robust to the evolution of the source schema. The defaulting rules are sufficiently powerful that in many cases a usable binding can be produced with no binding declarations at all. By defining a standardized format for the binding declarations, it is envisioned that tools will be built to greatly aid the process of customizing the binding from schema components to a Java representation.
3.3.2. Mapping Annotations
A mapping annotation defines the mapping of a program element to one or more schema components. A mapping annotation typically contains one or more annotation members to allow customized binding. An annotation member can be required or optional. A mapping annotation can be collocated with the program element in the source. The schema generator hence actually requires both inputs: a set of classes and a set of mapping annotations.
Defaults make it easy to use the mapping annotations. In the absence of a mapping annotation on a program element, the schema generator assumes, when required by a mapping rule, a default mapping annotation. This, together with an appropriate choice of default values for optional annotation members makes it possible to produce in many cases a usable mapping with minimal mapping annotations. Thus mapping annotations provide a powerful yet easy to use customization mechanism.
3.4. Annotations
Many of the architectural components are driven by program annotations defined by this specification, mapping annotations.
Java to Schema Mapping Mapping annotations provide meta data that describe or customize the mapping of existing classes to a derived schema.
Portable Value Classes Mapping annotations provide information for unmarshalling and marshalling of an XML instance into a content tree representing the XML content without the need for a schema at run time. Thus schema derived code annotated with mapping annotations are portable i.e. they are capable of being marshalled and unmarshalled by a universal marshaller and unmarshaller written by a JAXB vendor implementation.
Adding application specific behavior and data
Applications can choose to add either behavior or data to schema derived
code. Section Modifying Schema-Derived Code
specifies how the mapping annotation, @jakarta.annotation.Generated
,
should be used by a developer to denote developer added/modified code
from schema-derived code. This information can be utilized by tools to
preserve application specific code across regenerations of schema
derived code.
3.5. Binding Framework
The binding framework has been revised significantly since JAXB 1.0. Significant changes include:
-
support for unmarshalling of invalid XML content.
-
removal of on-demand validation.
-
unmarshal/marshal time validation deferring to JAXP validation.
3.5.1. Unmarshalling
3.5.1.1. Invalid XML Content
Rationale: Invalid XML content can arise for many reasons:
-
When the cost of validation needs to be avoided.
-
When the schema for the XML has evolved.
-
When the XML is from a non-schema-aware processor.
-
When the schema is not authoritative.
Support for invalid XML content required changes to JAXB 1.0 schema to java binding rules as well as the introduction of a flexible unmarshalling mode. These changes are described in Unmarshalling Modes.
3.5.2. Validation
The constraints expressed in a schema fall into three general categories:
-
A type constraint imposes requirements upon the values that may be provided by constraint facets in simple type definitions.
-
A local structural constraint imposes requirements upon every instance of a given element type, e.g., that required attributes are given values and that a complex element’s content matches its content specification.
-
A global structural constraint imposes requirements upon an entire document, e.g., that
ID
values are unique and that for everyIDREF
attribute value there exists an element with the correspondingID
attribute value.
A document is valid if, and only if, all of the constraints expressed in its schema are satisfied. The manner in which constraints are enforced in a set of derived classes has a significant impact upon the usability of those classes. All constraints could, in principle, be checked only during unmarshalling. This approach would, however, yield classes that violate the fail-fast principle of API design: errors should, if feasible, be reported as soon as they are detected. In the context of schema-derived classes, this principle ensures that violations of schema constraints are signalled when they occur rather than later on when they may be more difficult to diagnose.
With this principle in mind we see that schema constraints can, in general, be enforced in three ways:
-
Static enforcement leverages the type system of the Java programming language to ensure that a schema constraint is checked at application’s compilation time. Type constraints are often good candidates for static enforcement. If an attribute is constrained by a schema to have a boolean value, e.g., then the access methods for that attribute’s property can simply accept and return values of type
boolean
. -
Simple dynamic enforcement performs a trivial run-time check and throws an appropriate exception upon failure. Type constraints that do not easily map directly to Java classes or primitive types are best enforced in this way. If an attribute is constrained to have an integer value between zero and 100, e.g., then the corresponding property’s access methods can accept and return
int
values and its mutation method can throw a run-time exception if its argument is out of range. -
Complex dynamic enforcement performs a potentially costly run-time check, usually involving more than one content object, and throwing an appropriate exception upon failure. Local structural constraints are usually enforced in this way: the structure of a complex element’s content, e.g., can in general only be checked by examining the types of its children and ensuring that they match the schema’s content model for that element. Global structural constraints must be enforced in this way: the uniqueness of
ID
values, e.g., can only be checked by examining the entire content tree.
It is straightforward to implement both static and simple dynamic checks so as to satisfy the fail-fast principle. Constraints that require complex dynamic checks could, in theory, also be implemented so as to fail as soon as possible. The resulting classes would be rather clumsy to use, however, because it is often convenient to violate structural constraints on a temporary basis while constructing or manipulating a content tree.
Consider, e.g., a complex type definition whose content specification is very complex. Suppose that an instance of the corresponding value class is to be modified, and that the only way to achieve the desired result involves a sequence of changes during which the content specification would be violated. If the content instance were to check continuously that its content is valid, then the only way to modify the content would be to copy it, modify the copy, and then install the new copy in place of the old content. It would be much more convenient to be able to modify the content in place.
A similar analysis applies to most other sorts of structural constraints, and especially to global structural constraints. Schema-derived classes have the ability to enable or disable a mode that verifies type constraints. JAXB mapped classes can optionally be validated at unmarshal and marshal time.
3.5.2.1. Validation Re architecture
The detection of complex schema constraint
violations has been redesigned to have a Jakarta XML Binding implementation to
delegate to the validation API in JAXP. JAXP defines a standard
validation API (javax.xml.validation
package) for validating XML
content against constraints within a schema. Furthermore, JAXP has
been incorporated into J2SE 5.0 platform. Any Jakarta XML Binding implementation
that takes advantage of the validation API will result in a smaller
footprint.
3.5.2.2. Unmarshal validation
When the unmarshalling process incorporates validation and it successfully completes without any validation errors, both the input document and the resulting content tree are guaranteed to be valid.
However, always requiring validation during unmarshalling proves to be too rigid and restrictive a requirement. Since existing XML parsers allow schema validation to be disabled, there exist a significant number of XML processing uses that disable schema validation to improve processing speed and/or to be able to process documents containing invalid or incomplete content. To enable the JAXB architecture to be used in these processing scenarios, the binding framework makes validation optional.
3.5.2.3. Marshal Validation
Validation may also be optionally performed at marshal time. This is new for Jakarta XML Binding. Validation of object graph while marshalling is useful in web services where the marshalled output must conform to schema constraints specified in a WSDL document. This could provide a valuable debugging aid for dealing with any interoperability problems
3.5.2.4. Handling Validation Failures
While it would be possible to notify a JAXB
application that a validation error has occurred by throwing a
JAXBException
when the error is detected, this means of communicating
a validation error results in only one failure at a time being handled.
Potentially, the validation operation would have to be called as many
times as there are validation errors. Both in terms of validation
processing and for the application’s benefit, it is better to detect as
many errors and warnings as possible during a single validation pass. To
allow for multiple validation errors to be processed in one pass, each
validation error is mapped to a validation error event. A validation
error event relates the validation error or warning encountered to the
location of the text or object(s) involved with the error. The stream of
potential validation error events can be communicated to the application
either through a registered validation event handler at the time the
validation error is encountered, or via a collection of validation
failure events that the application can request after the operation has
completed.
Unmarshalling and marshalling are the two operations that can result in multiple validation failures. The same mechanism is used to handle both failure scenarios. See General Validation Processing for further details.
3.6. An example
Throughout this specification we will refer and build upon the familiar schema from [XSD Part 0], which describes a purchase order, as a running example to illustrate various binding concepts as they are defined. Note that all schema name attributes with values in this font are bound by JAXB technology to either a Java interface or JavaBean-like property. Please note that the derived Java code in the example only approximates the default binding of the schema-to-Java representation.
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
<xsd:element name="comment" type="xsd:string"/>
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="items" type="Items"/>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
<xsd:complexType name="USAddress">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="street" type="xsd:string"/>
<xsd:element name="city" type="xsd:string"/>
<xsd:element name="state" type="xsd:string"/>
<xsd:element name="zip" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
</xsd:complexType>
<xsd:complexType name="Items" >
<xsd:sequence>
<xsd:element name="item" minOccurs="1" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="productName" type="xsd:string"/>
<xsd:element name="quantity" >
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:maxExclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="USPrice" type="xsd:decimal"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
</xsd:sequence>
<xsd:attribute name="partNum" type="SKU" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
<!-- Stock Keeping Unit, a code for identifying products -->
<xsd:simpleType name="SKU" >
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{3}-[A-Z]{2}"/>
</xsd:restriction
</xsd:simpleType>
</xsd:schema>
Binding of purchase order schema to a Java representation[1]:
import javax.xml.datatype.XMLGregorianCalendar; import java.util.List;
public class PurchaseOrderType {
USAddress getShipTo() {...} void setShipTo(USAddress) {...}
USAddress getBillTo() {...} void setBillTo(USAddress) {...}
/** Optional to set Comment property. */
String getComment() {...} void setComment(String) {...}
Items getItems() {...} void setItems(Items) {...}
XMLGregorianCalendar getOrderDate() void setOrderDate(XMLGregorianCalendar)
};
public class USAddress {
String getName() {...} void setName(String) {...}
String getStreet() {...} void setStreet(String) {...}
String getCity() {...} void setCity(String) {...}
String getState() {...} void setState(String) {...}
int getZip() {...} void setZip(int) {...}
static final String COUNTRY=”USA”;[2]
};
public class Items {
public class ItemType {
String getProductName() {...} void setProductName(String) {...}
/** Type constraint on Quantity setter value 0..99.[3] */
int getQuantity() {...} void setQuantity(int) {...}
float getUSPrice() {...} void setUSPrice(float) {...}
/** Optional to set Comment property. */
String getComment() {...} void setComment(String) {...}
XMLGregorianCalendar getShipDate(); void setShipDate(XMLGregorianCalendar);
/** Type constraint on PartNum setter value "\d{3}-[A-Z]{2}".[2] */
String getPartNum() {...} void setPartNum(String) {...}
};
/** Local structural constraint 1 or more instances of Items.ItemType */
List<Items.ItemType> getItem() {...}
}
public class ObjectFactory {
// type factories
Object newInstance(Class javaInterface) {...}
PurchaseOrderType createPurchaseOrderType() {...}
USAddress create USAddress() {...}
Items createItems() {...}
Items.ItemType createItemsItemType() {...}
// element factories
JAXBElement<PurchaseOrderType> createPurchaseOrder(PurchaseOrderType) {...}
JAXBElement<String> createComment(String value) {...}
}
The purchase order schema does not describe any global structural constraints.
The coming chapters will identify how these XML Schema concepts were bound to a Java representation. Just as in [XSD Part 0], additions will be made to the schema example to illustrate the binding concepts being discussed.
4. The Binding Framework
The binding framework defines APIs to
access unmarshalling, validation and marshalling operations for
manipulating XML data and JAXB mapped objects. The framework is
presented here in overview; its full specification is available in the
javadoc for the package jakarta.xml.bind
.
The binding framework resides in two main
packages. The jakarta.xml.bind
package defines abstract classes and
interfaces that are used directly with content classes. The
jakarta.xml.bind
package defines the
Unmarshaller
, Marshaller
and Binder
classes, which are auxiliary
objects for providing their respective operations.
The JAXBContext
class is the entry point
for a Java application into the JAXB framework. A JAXBContext
instance
manages the binding relationship between XML element names to Java value
class for a JAXB implementation to be used by the unmarshal, marshal and
binder operations. The jakarta.xml.bind.helper
package provides partial
default implementations for some of the jakarta.xml.bind
interfaces.
Implementations of JAXB technology can extend these classes and
implement the abstract methods. These APIs are not intended to be used
directly by applications using the JAXB architecture. A third package,
jakarta.xml.bind.util
, contains utility classes that may be used
directly by client applications.
The binding framework defines a hierarchy of exception and validation event classes for use when marshalling/unmarshalling errors occur, when constraints are violated, and when other types of errors are detected.
4.1. Annotation-driven Binding Framework
The portability of JAXB annotated classes is achieved via an annotation-driven architecture. The program annotations, specified in Section 8, describe the mapping from the Java program elements to XML Schema components. This information is used by the binding framework to unmarshal and marshal to XML content into/from JAXB-annotated classes. All JAXB schema binding compilers must be able to generate portable schema-derived JAXB-annotated classes following the constraints described in Binding XML Schema to Java Representations. All binding runtime frameworks are required to be able to marshal and unmarshal portable JAXB-annotated classes generated by other Jakarta XML Binding schema binding compiler.
It is not possible to require portability of the interface/implementation binding from JAXB 1.0. For backwards compatibility with existing implementations, that binding remains a tight coupling between the schema-derived implementation classes and the JAXB implementation’s runtime framework. Users are required to regenerate the schema-derived implementation classes when changing JAXB implementations.
4.2. JAXBContext
The JAXBContext
class provides the client’s
entry point to the JAXB API. It provides an abstraction for managing the
XML/Java binding information necessary to implement the JAXB binding
framework operations: unmarshal and marshal.
The following summarizes the JAXBContext
class defined in package jakarta.xml.bind
.
public abstract class JAXBContext {
static final String JAXB_CONTEXT_FACTORY;
static JAXBContext newInstance(String contextPath);
static JAXBContext newInstance(String contextPath,
ClassLoader contextPathCL);
static JAXBContext newInstance(Class... classesToBeBound);
abstract Unmarshaller createUnmarshaller();
abstract Marshaller createMarshaller();
abstract JAXBIntrospector createJAXBIntrospector();
<T> Binder<T> createBinder(Class<T> domType);
Binder<org.w3c.dom.Node> createBinder();
void generateSchema(SchemaOutputResolver);
}
To avoid the overhead involved in creating a JAXBContext instance, a JAXB application is encouraged to reuse a JAXBContext instance. An implementation of abstract class JAXBContext is required to be thread-safe, thus, multiple threads in an application can share the same JAXBContext instance.
A client application configures a JAXBContext
using the JAXBContext.newInstance(String contextPath)
factory method.
JAXBContext jc =
JAXBContext.newInstance( "com.acme.foo:com.acme.bar" );
The above example initializes a JAXBContext
with the schema-derived Java packages com.acme.foo
and com.acme.bar
.
A jaxb.index
resource file, described in more detail in the javadoc,
list the non-schema-derived classes, namely the java to schema binding,
in a package to register with JAXBContext
. Additionally, in each
specified directory, if an optional resource file[4]
containing package level mapping annotations exist, it is incorporated
into the JAXBContext representation.
An alternative mechanism that could be more convenient when binding Java classes to Schema is to initialize JAXBContext by passing JAXB-annotated class objects.
JAXBContext jc =
JAXBContext.newInstance( POElement.class );
The classes specified as parameters to
newInstance
and all classes that are directly/indirectly referenced
statically from the specified classes are included into the returned
JAXBContext
instance. For each directory of all the classes imported
into JAXBContext, if an optional resource file[4] containing package level
mapping annotations exists, it is incorporated into the JAXBContext
representation.
For example, given the following Java classes:
@XmlRootElement class Foo { Bar b; }[5]
@XmlType class Bar { FooBar fb; }
@XmlType class FooBar { int x; }
The invocation of
JAXBContext.newInstance(Foo.class)
registers Foo and the statically
referenced classes, Bar
and FooBar
.
Note that the jaxb.index resource file is not
necessary when an application uses
JAXBContenxt.newInstances(Class…classesToBeBound)
.
For either scenario, the values of these parameters initialize the JAXBContext object so that it is capable of managing the JAXB mapped classes.
See the javadoc for JAXBContext
for more details on using this class.
Design Note
JAXBContext class is designed to be immutable and thus thread-safe. Given the amount of dynamic processing that potentially could take place when creating a new instance of JAXBContxt, it is recommended that a JAXBContext instance be shared across threads and reused as much as possible to improve application performance. |
Note
If JAXB-annotated classes or packages referenced in context path
are defined in a Java Platform Module System (JSR 376) module,
they must be open (as specified in javadoc of |
4.3. General Validation Processing
Three identifiable forms of validation exist within the JAXB architecture include:
-
Unmarshal-time validation
This form of validation enables a client application to be notified of validation errors and warnings detected while unmarshalling XML data into a Java content tree and is completely orthogonal to the other types of validation. See jakarta.xml.bind.Unmarshaller javadoc for a description on how to enable this feature. -
On-demand validation
This mode of validation is not defined in Jakarta XML Binding Specification. -
Fail-fast validation
This form of validation enables a client application to receive immediate feedback about a modification to the Java content tree that violates a type constraint of a Java property. An unchecked exception is thrown if the value provided to a set method is invalid based on the constraint facets specified for the basetype of the property. This style of validation is optional in this version of the specification. Of the JAXB implementations that do support this type of validation, it is customization-time decision to enable or disable fail-fast validation when setting a property.
Unmarshal-time uses an event-driven mechanism to enable multiple validation errors and warnings to be processed during a single operation invocation. If the validation or unmarshal operation terminates with an exception upon encountering the first validation warning or error, subsequent validation errors and warnings would not be discovered until the first reported error is corrected. Thus, the validation event notification mechanism provides the application a more powerful means to evaluate validation warnings and errors as they occur and gives the application the ability to determine when a validation warning or error should abort the current operation (such as a value outside of the legal value space). Thus, an application could allow locally constrained validation problems to not terminate validation processing.
If the client application does not set an
event handler on a Unmarshaller
or Marshaller
instance prior to
invoking the unmarshal
or marshal
operations, then a default event
handler will receive notification of any errors or fatal errors
encountered and stop processing the XML data. In other words, the
default event handler will fail on the first error that is encountered.
There are three ways to handle validation events encountered during the unmarshal and marshal operations:
-
Rely on the default validation event handler
The default handler will fail on the first error or fatal error encountered. -
Implement and register a custom validation event handler
Client applications that require sophisticated event processing can implement theValidationEventHandler
interface and register it with the Validator or Unmarshaller instance respectively. -
Request an error/warning event list after the operation completes
By registering theValidationEventCollector
helper, a specialized event handler, with thesetEventHandler
method, theValidationEvent
objects created during the unmarshal and marshal operations are collected. The client application can then request the list after the operation completes.
Validation events are handled differently
depending on how the client application is configured to process them as
described previously. However, there are certain cases where a JAXB
implementation may need to indicate that it is no longer able to
reliably detect and report errors. In these cases, the JAXB
implementation will set the severity of the ValidationEvent
to
FATAL_ERROR
to indicate that the unmarshal
or validate
operation
should be terminated. The default event handler and
ValidationEventCollector
helper class must terminate processing after
being notified of a fatal error. Client applications that supply their
own ValidationEventHandler
should also terminate processing after
being notified of a fatal error. If not, unexpected behavior may occur.
4.4. Unmarshalling
The Unmarshaller
class governs the process
of deserializing XML data into a Java content tree, capable of
validating the XML data as it is unmarshalled. It provides the basic
unmarshalling methods:
public interface Unmarshaller {
ValidationEventHandler getEventHandler()
void setEventHandler(ValidationEventHandler)
java.lang.Object getProperty(java.lang.String name)
void setProperty(java.lang.String name, java.lang.Object value)
void setSchema(javax.xml.validation.Schema schema)
javax.xml.validation.Schema getSchema()
UnmarshallerHandler getUnmarshallerHandler()
void setListener(Unmarshaller.Listener)
Unmarshaller.Listener getListener()
java.lang.Object unmarshal(java.io.File)
java.lang.Object unmarshal(java.net.URL)
java.lang.Object unmarshal(java.io.InputStream)
java.lang.Object unmarshal(org.xml.sax.InputSource)
java.lang.Object unmarshal(org.w3c.dom.Node)
java.lang.Object unmarshal(javax.xml.transform.Source)
java.lang.Object unmarshal(javax.xml.stream.XMLStreamReader)
java.lang.Object unmarshal(javax.xml.stream.XMLEventReader)
<T> JAXBElement<T> unmarshal(org.w3c.dom.Node,
Class<T> declaredType)
<T> JAXBElement<T> unmarshal(javax.xml.transform.Source,
Class<T> declaredType)
<T> JAXBElement<T> unmarshal(javax.xml.stream.XMLStreamReader,
Class<T> declaredType)
<T> JAXBElement<T> unmarshal(javax.xml.stream.XMLEventReader,
Class<T> declaredType)
}
The JAXBContext
class contains a factory to
create an Unmarshaller
instance. The JAXBContext
instance manages
the XML/Java binding data that is used by unmarshalling. If the
JAXBContext
object that was used to create an Unmarshaller
does not
know how to unmarshal the XML content from a specified input source,
then the unmarshal
operation will abort immediately by throwing an
UnmarshalException
. There are six convenience methods for
unmarshalling from various input sources.
An application can enable or disable
unmarshal-time validation by enabling JAXP validation via the
setSchema(javax.xml.validation.Schema)
method. The application has the
option to customize validation error handling by overriding the default
event handler using the setEventHandler(ValidationEventHandler)
. The
default event handler aborts the unmarshalling process when the first
validation error event is encountered. Validation processing options are
presented in more detail in General Validation Processing.
An application has the ability to specify a
SAX 2.0 parser to be used by the unmarshal
operation using the
unmarshal(javax.xml.transform.Source)
method. Even though the JAXB
provider’s default parser is not required to be SAX2.0 compliant, all
providers are required to allow an application to specify their own
SAX2.0 parser. Some providers may require the application to specify the
SAX2.0 parser at binding compile time. See the method javadoc
unmarshal(Source)
for more detail on how an application can specify
its own SAX 2.0 parser.
The getProperty
/setProperty
methods
introduce a mechanism to associate implementation specific
property/value pairs to the unmarshalling process. At this time there
are no standard JAXB properties specified for the unmarshalling process.
4.4.1. Unmarshal event callbacks
The Unmarshaller
provides two styles of
callback mechanisms that allow application specific processing during
key points in the unmarshalling process. In 'class-defined' event
callbacks, application specific code placed in JAXB mapped classes is
triggered during unmarshalling. External listeners allow for centralized
processing of unmarshal events in one callback method rather than by
type event callbacks. The 'class defined' and external listener event
callback methods are independent of each other, both can be called for
one event. The invocation ordering when both listener callback methods
exist is defined in jakarta.xml.bind.Unmarshaller.Listener
javadoc.
Event callback methods should be written with following considerations. Each event callback invocation contributes to the overall unmarshal time. An event callback method throwing an exception terminates the current unmarshal process.
4.4.1.1. Class-defined
A JAXB mapped class can optionally implement the following unmarshal event callback methods.
-
private void beforeUnmarshal(Unmarshaller, Object parent)
This method is called immediately after the object is created and before the unmarshalling of this object begins.The callback provides an opportunity to initialize JavaBean properties prior to unmarshalling.-
Parameters:
unmarshaller
- unmarshal context.
parent
- points to the parent object to which this object will be set. Parent is null when this object is the root object.
-
-
private void afterUnmarshal(Unmarshaller, Object parent)
This method is called after all the properties (except IDREF) are unmarshalled for this object, but before this object is set to the parent object.-
Parameters:
unmarshaller
- unmarshal context.
parent
- points to the parent object to which this object will be set. Parent is null when this object is the root object.
-
These callback methods allow an object to perform additional processing at certain key point in the unmarshalling operation.
4.4.1.2. External Listener
The external listener callback mechanism
enables the registration of a Unmarshaller.Listener
instance with an
Unmarshaller.setListener(Unmarshaller.Listener)
. The external
listener receives all callback events, allowing for more centralized
processing than per class defined callback methods. The external
listener receives events when unmarshalling to a JAXB element or to JAXB
mapped class.
4.4.2. Unmarshalling Modes
There exist numerous use cases requiring the ability to unmarshal invalid XML content. A flexible unmarshalling mode is described in this version of the specification to enable predictable unmarshalling of invalid content. The previous unmarshalling mode implied by JAXB 1.0 specification is named structural unmarshalling. This unmarshalling mode was well defined for the unmarshalling of valid XML content and allowed an implementation to handle invalid XML content in anyway that it choose to.
Both of these modes have benefits and drawbacks based on an application’s xml processing needs.
4.4.3. Structural Unmarshalling
Some of the XML Schema to Java bindings in
JAXB 1.0 implied that an unmarshaller had to maintain a state machine,
implying that the order of elements had to match up exactly as described
by the schema or unmarshaller would work unpredictably. When this
unmarshalling process detects a structural inconsistency that it is
unable to recover from, it should abort the unmarshal process by
throwing UnmarshalException
.
For example, it was valid for a Jakarta XML Binding implementation to rigidly give up unmarshalling an invalid XML document once it came across an unexpected element/attribute or missed a required element or attribute. This mode appeals to users who prefer to be notified that an xml document is deviating from the schema.
XML Schema to Java binding for interfaces and implementation classes, Java Content Interface, can implement either structural unmarshalling or flexible unmarshalling.
4.4.4. Flexible Unmarshalling
To address the rigidness of structural unmarshalling, flexible unmarshalling mode is specified to enable greater predictability in unmarshalling invalid XML content. It unmarshals xml content by element name, rather than strictly on the position of the element within a content model. This allows this mode to handle the following cases:
-
elements being out of order in a content model
-
recovering from required elements/attributes missing from an xml document
-
ignoring unexpected elements/attributes in an xml document
In order to enable this mode, the following JAXB 1.0 customized bindings that required state-driven unmarshalling have been removed from this specification.
-
Binding a model group or model group definition to a Java class.
Since there is no XML infoset information denoting these schema components, a model group can only be inferred by applying positional schema constraints to a valid XML document, tracking position within a valid content model. -
Multiple occurrences of an element name in a content model can no longer be mapped to different JAXB properties. Instead the entire content model is bound to a general content model.
The removal of these bindings greatly assists the error recovery for structural unmarshalling mode.
Flexible unmarshalling appeals to those who need to be able to perform best match unmarshalling of invalid xml documents.
The flexible unmarshalling process is annotation driven. This process is specified in Runtime Processing. Flexible unmarshalling is required for Jakarta XML Binding annotated classes.
4.5. Marshalling
The Marshaller
class is responsible for
governing the process of serializing a Java content tree into XML data.
It provides the basic marshalling methods:
interface Marshaller {
string JAXB_ENCODING;
string JAXB_FORMATTED_OUTPUT;
string JAXB_SCHEMA_LOCATION;
string JAXB_NO_NAMESPACE_SCHEMA_LOCATION;
string JAXB_FRAGMENT;
<PROTENTIALLY MORE PROPERTIES...>
java.lang.Object getProperty(java.lang.String name)
void setProperty(java.lang.String name, java.lang.Object value)
void setEventHandler(ValidationEventHandler handler)
ValidationEventHandler getEventHandler()
void setSchema(javax.xml.validation.Schema schema)
javax.xml.validation.Schema getSchema()
void setListener(Unmarshaller.Listener)
Unmarshaller.Listener getListener()
void marshal(java.lang.Object e, java.io.Writer writer)
void marshal(java.lang.Object e, java.io.OutputStream os)
void marshal(java.lang.Object e, org.xml.sax.ContentHandler)
void marshal(java.lang.Object e, javax.xml.transform.Result)
void marshal(java.lang.Object e, org.w3c.dom.Node)
void marshal(java.lang.Object e,
javax.xml.stream.XMLStreamWriter writer)
org.w3c.dom.Node getNode(java.lang.Object contentTree)
}
The JAXBContext
class contains a factory to
create a Marshaller
instance. Convenience method overloading of the
marshal()
method allow for marshalling a content tree to common Java
output targets and to common XML output targets of a stream of SAX2
events or a DOM parse tree.
Although each of the marshal methods accepts
a java.lang.Object
as its first parameter, JAXB implementations are
not required to be able to marshal any arbitrary java.lang.Object
. If
the first parameter is not a JAXB element, as determined by
JAXBIntrospector.isElement()
method, the marshal operation must throw
a MarshalException
. There exist two mechanisms to enable marshalling
an instance that is not a JAXB element. One method is to wrap the
instance as the value of a jakarta.xml.bind.JAXBElement
instance, and
pass the wrapper element as the first parameter to a marshal
method.
For java to schema binding, it is also possible to simply annotate the
instance’s class with the appropriate program annotation,
@XmlElementRoot
, specified in Section 8.
The marshalling process can optionally be
configured to validate the content tree being marshalled. An application
can enable or disable marshal-time validation by enabling JAXP
validation via the setSchema(javax.xml.validation.Schema)
method. The
application has the option to customize validation error handling by
overriding the default event handler using the
setEventHandler(ValidationEventHandler)
. The default event handler
aborts the marshalling process when the first validation error event is
encountered. Validation processing options are presented in more detail
in General Validation Processing.
There is no requirement that the Java content
tree be valid with respect to its original schema in order to marshal it
back into XML data. If the marshalling process detects a structural
inconsistency during its process that it is unable to recover from, it
should abort the marshal process by throwing MarshalException
. The
marshalling process of a JAXB-annotated class is annotation driven. This
process is specified in Runtime Processing.
4.5.1. Marshal event callbacks
The Marshaller provides two styles of
callback mechanisms that allow application specific processing during
key points in the marshalling process. In class-defined event callbacks,
application specific code placed in JAXB mapped classes is triggered
during marshalling. External listeners allow for centralized processing
of marshal events in one callback method rather than by type event
callbacks. The invocation ordering when both listener callback methods
exist is defined in jakarta.xml.bind.Marshaller.Listener
javadoc.
Event callback methods should be written with following considerations. Each event callback invocation contributes to the overall marshal time. An event callback method throwing an exception terminates the current marshal process.
4.5.1.1. Class-defined
A JAXB mapped class can optionally implement the following marshal event callback methods.
-
private void beforeMarshal(Marshaller)
This method is called before the marshalling of this object starts.-
Parameters:
marshaller
- marshal context.
-
-
private void afterMarshal(Marshaller)
This method is called after the marshalling of this object (and all its descendants) has finished.-
Parameters:
marshaller
- marshal context.
-
These callback methods allow the customization of an JAXB mapped class to perform additional processing at certain key point in the marshalling operation. The 'class defined' and external listener event callback methods are independent of each other, both can be called for one event.
An event callback method throwing an exception terminates the current marshal process.
4.5.1.2. External Listener
The external listener callback mechanism
enables the registration of a Marshaller.Listener
instance with a
Marshaller.setListener(Marshaller.Listener)
. The external listener
receives all callback events, allowing for more centralized processing
than per class-defined callback methods.
4.5.2. Marshalling Properties
The following subsection highlights properties that can be used to control the marshalling process. These properties must be set prior to the start of a marshalling operation: the behavior is undefined if these attributes are altered in the middle of a marshalling operation. The following standard properties have been identified:
-
jaxb.encoding
output character encoding. If the property is not specified, it defaults to "UTF-8". -
jaxb.formatted.output
true
- human readable indented xml data
false
- unformatted xml data
If the property is not specified, it defaults tofalse
. -
jaxb.schemaLocation
This property allows the client application to specify anxsi:schemaLocation
attribute in the generated XML data. -
jaxb.noNamespaceSchemaLocation
This property allows the client application to specify anxsi:noNamespaceSchemaLocation
attribute in the generated XML data. -
jaxb.fragment
Its value must be a java.lang.Boolean. This property determines whether or not document level events will be generated by the Marshaller. If this property is not defined, it defaults tofalse
.
4.6. JAXBIntrospector
This class provides access to key XML mapping information of a JAXB mapped instance.
public abstract class JAXBIntrospector {
public boolean isElement(Object jaxbObj);
public QName getElementName(Object jaxbElement);
public static Object getValue(Object jaxbElement);
}
The Jakarta XML Binding architecture has two uniquely different ways to represent an XML element.The XML Schema to Java binding for an XML element declaration is described in Java Element Representation. The Java to XML Schema binding for an XML element declaration is described in @XmlRootElement.
Use JAXBInstrospector.isElement(Object)
method to determine if an instance of a JAXB mapped class represents an
XML element. One can get the xml element tag name associated with a JAXB
element using JAXBIntrospector.getElementName
method. One can an xml
element’s value using getValue method. The getValue method normalizes
access of JAXB element, hiding whether the JAXB element is an instance
of jakarta.xml.bind.JAXBElement or if it is an JAXB element via an
@XmlRootElement class annotation.
4.7. Validation Handling
Methods defined in the binding framework can
cause validation events to be delivered to the client application’s
ValidationEventHandler.Setter
methods generated in schema-derived
classes are capable of throwing TypeConstraintExceptions
, all of
which are defined in the binding framework.
The following list describes the primary event and constraint-exception classes:
-
An instance of a
TypeConstraintException
subclass is thrown when a violation of a dynamically-checked type constraint is detected. Such exceptions will be thrown by property-set methods, for which it would be inconvenient to have to handle checked exceptions; type-constraint exceptions are therefore unchecked, i.e, this class extendsjava.lang.RuntimeException
. The constraint check is always performed prior to the property-set method updating the value of the property, thus if the exception is thrown, the property is guaranteed to retain the value it had prior to the invocation of the property-set method with an invalid value. This functionality is optional to implement in this version of the specification. Additionally, a customization mechanism is provided to control enabling and disabling this feature. -
An instance of a
ValidationEvent
is delivered whenever a violation is detected during optionally enabled unmarshal/marshal validation. Additionally,ValidationEvents
can be discovered during marshalling such as ID/IDREF violations and print conversion failures. These violations may indicate local and global structural constraint violations, type conversion violations, type constraint violations, etc. -
Since the unmarshal operation involves reading an input document, lexical well-formedness errors may be detected or an I/O error may occur. In these cases, an
UnmarshalException
will be thrown to indicate that the JAXB provider is unable to continue the unmarshal operation. -
During the marshal operation, the JAXB provider may encounter errors in the Java content tree that prevent it from being able to complete. In these cases, a
MarshalException
will be thrown to indicate that the marshal operation can not be completed.
4.8. DOM and Java representation Binding
The Binder class is responsible for maintaining the relationship between a infoset preserving view of an XML document with a possibly partial binding of the XML document to a JAXB representation. Modifications can be made to either the infoset preserving view or the JAXB representation of the document while the other view remains unmodified. The binder is able to synchronize the changes made in the modified view back into the read-only view. When synchronizing changes to JAXB view back to related xml infoset preserving view, every effort is made to preserve XML concepts that are not bound to JAXB objects, such as XML infoset comments, processing instructions, namespace prefix mappings, etc.
4.8.1. Use Cases
-
Read-only partial binding.
Application only needs to manipulate a small part of a rather large XML document. It suffices to only map the small of the large document to the JAXB Java representation. -
Updateable partial binding
The application receives an XML document that follows a later version of the schema than the application is aware of. The parts of the schema that the application needs to read and/or modify have not changed. Thus, the document can be read into an infoset preserving representation, such as DOM, only bind the part of the document that it does still have the correct schema for into the JAXB Java representation of the fragment of the document using Binder.unmarshal from the DOM to the JAXB view. Modify the partial Java representation of the document and then synchronize the modified parts of the Java representation back to the DOM view usingBinder.updateXML
method. -
XPATH navigation
Given that binder maintains a relationship between XML infoset view of document and JAXB representation, one can use JAXP XPATH on the XML infoset view and use the binder’s associative mapping to get from the infoset node to JAXB representation.
4.8.2. jakarta.xml.bind.Binder
The class jakarta.xml.bind.Binder
associates
an infoset preserving representation of the entire XML document with a
potentially partial binding to a Java representation. The binder
provides operations to synchronize between the two views that it is
binding.
public abstract class Binder<XmlNode> {
// Create two views of XML content, infoset view and JAXB view.
public abstract Object unmarshal(XmlNode xmlNode)
<T> JAXBElement<T> unmarshal(XmlNode xmlNode,
Class<T> declaredType)
public abstract void marshal(Object jaxbObject, XmlNode xmlNode)
// Navigation between xml infoset view and JAXB view.
public abstract XmlNode getXMLNode(Object jaxbObject);
public abstract Object getJAXBNode(XmlNode xmlNode);
// Synchronization methods
public abstract XmlNode updateXML(Object jaxbObject)
public abstract XmlNode updateXML(Object jaxbObject, XmlNode xmlNode)
throws JAXBException;
public abstract Object updateJAXB(XmlNode xmlNode)
throws JAXBException;
// Enable optional validation
public abstract void setSchema(Schema schema);
public abstract Schema getSchema();
public abstract void setEventHandler(ValidationEventHandler handler)
throws JAXBException;
public abstract ValidationEventHandler getEventHandler()
throws JAXBException;
// Marshal/Unmarshal properties
public abstract void setProperty(String name, Object value)
throws PropertyException;
public abstract Object getProperty(String name)
throws PropertyException;
}
4.9. Implementation discovery
To create an instance of JAXBContext,
one of JAXBContext.newInstance
methods is invoked. JAXB implementation
discovery happens each time JAXBContext.newInstance
is invoked.
Implementation discovery consists of following steps in the order specified (first successful resolution applies):
-
If the system property
jakarta.xml.bind.JAXBContextFactory
exists, then its value is assumed to be the provider factory class. This phase of the look up enables per-JVM override of the Jakarta XML Binding implementation. -
If the property
jakarta.xml.bind.JAXBContextFactory
exists in theMap<String, ?>
passed toJAXBContext.newInstance(Class[], Map)
or toJAXBContext.newInstance(String, ClassLoader, Map)
, then its value is assumed to be the fully qualified provider factory class name. This phase of the look up enables context sensitive selection of the Jakarta XML Binding implementation. -
Provider of
jakarta.xml.bind.JAXBContextFactory
is loaded using the service-provider loading facilities, as defined by Java SE Platform, to attempt to locate and load an implementation of the service. -
Finally, if all of the steps above fail, then the rest of the look up is unspecified.
Once the provider factory class is discovered, context creation is delegated to one of its createContext(…) methods.
5. Java Representation of XML Content
This section defines the basic binding representation of package, value class, element classes, properties and enum type within the Java programming language. Each section briefly states the XML Schema components that could be bound to the Java representation. A more rigorous and thorough description of possible bindings and default bindings occurs in Binding XML Schema to Java Representations and in Customizing XML Schema to Java Representation Binding.
5.1. Mapping between XML Names and Java Identifiers
XML schema languages use XML names, i.e., strings that match the Name production defined in XML 1.0 (Second Edition) to label schema components. This set of strings is much larger than the set of valid Java class, method, and constant identifiers. Binding XML Names to Java Identifiers, specifies an algorithm for mapping XML names to Java identifiers in a way that adheres to standard Java API design guidelines, generates identifiers that retain obvious connections to the corresponding schema, and results in as few collisions as possible. It is necessary to rigorously define a standard way to perform this mapping so all implementations of this specification perform the mapping in the same compatible manner.
5.2. Java Package
Just as the target XML namespace provides a naming context for the named type definitions, named model groups, global element declarations and global attribute declarations for a schema vocabulary, the Java package provides a naming context for Java interfaces and classes. Therefore, it is natural to map the target namespace of a schema to be the package that contains the Java value class representing the structural content model of the document.
A package consists of:
-
A name , which is either derived directly from the XML namespace URI as specified in Generating a Java package name or specified by a binding customization of the XML namespace URI as described in Package.
-
A set of Java value classes representing the content models declared within the schema.
-
A set of Java element classes representing element declarations occurring within the schema. Java Element Representation describes this binding in more detail.
-
A public class
ObjectFactory
contains:-
An instance factory method signature for each Java content within the package.
Given Java value class named Foo, here is the derived factory method:public Foo createFoo();
-
An element instance factory method signature for each bound element declaration.
public JAXBElement<T> createFoo(T elementValue);
-
Dynamic instance factory allocator method signature:
public Object newInstance(Class javaContentInterface);
-
Property setter/getter
Provide the ability to associate implementation specific property/value pairs with the instance creation process.java.lang.Object getProperty(String name); void setProperty(String name, Object value);
-
-
A set of enum types.
-
Package javadoc.
Example:
Purchase Order Schema fragment with targetNamespace
:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:po="http://www.example.com/PO1"
targetNamespace="http://www.example.com/PO1">
<xs:element name="purchaseOrder" type="po:PurchaseOrderType"/>
<xs:element name="comment" type="xs:string"/>
<xs:complexType name="PurchaseOrderType"/>
...
</xs:schema>
Default derived Java code:
package com.example.PO1;
import jakarta.xml.bind.JAXBElement;
public class PurchaseOrderType {...};
public Comment { String getValue() {...} void setValue(String) {...} }
...
public class ObjectFactory {
PurchaseOrderType createPurchaseOrderType();
JAXBElement<PurchaseOrderType> createPurchaseOrder(PurchaseOrderType elementValue);
Comment createComment(String value);
...
}
5.3. Enum Type
A simple type definition whose value space is constrained by enumeration facets can be bound to a Java enum type. Enum type was introduced in J2SE 5.0 and is described in Section 8.9 of [JLS]. Enum type is a significant enhancement over the typesafe enum design pattern that it was designed to replace. If an application wishes to refer to the values of a class by descriptive constants and manipulate those constants in a type safe manner, it should consider binding the XML component containing enumeration facets to an enum type.
An enum type consists of:
-
A name , which is either computed directly from an XML name or specified by a binding customization for the schema component.
-
A package name, which is either computed from the target namespace of the schema component or specified within a binding declaration as a customization of the target namespace or a specified package name for components that are scoped to no target namespace.
-
Outer Class Names is “.” separated list of outer class names.
By default, if the XML component containing a typesafe enum class to be generated is scoped within a complex type as opposed to a global scope, the typesafe enum class should occur as a nested class within the Java value class representing the complex type scope.
Absolute class name is PackageName.[OuterClassNames.]Name.
Note: Outer Class Name is null if class is a top-level class.
The schema customization <jaxb:globalBindings localScoping=”toplevel”/>, specified in Section Usage, disables the generation of schema-derived nested classes and can be used to override the default binding of a nested schema component binding to nested Java class. -
A set of enum constants.
-
Class javadoc is a combination of a documentation annotation from the schema component and/or javadoc specified by customization.
An enum constant consists of:
-
A name, which is either computed from the enumeration facet value or specified by customization.
-
A value for the constant. Optimally, the name is the same as the value. This optimization is not possible when the enumeration facet value is not a valid Java identifier.
-
A datatype for the constant’s value.
-
Javadoc for the constant field is a combination of a documentation annotation for an enumeration value facet and/or javadoc specified by customization.
5.4. Content Representation
A complex type definition is bound to either
a Java value class or a content interface, depending on the value of the
global binding customization [jaxb:globalBinding]
@generateValueClass
, specified in Usage.
Value classes are generated by default. The attributes and
children element content of a complex type definition are represented as
properties of the Java content representation. Property representations
are introduced in Properties.
5.4.1. Value Class
A value class consists of:
-
A name , which is either computed directly from an XML name or specified by a binding customization for the schema component.
-
A package name, which is either computed from the target namespace of the schema component or specified by a binding customization of the target namespace or a specified package name for components that are scoped to no target namespace.
-
The outer class name context, a dot-separated list of Java class names.
By default, if the XML schema component for which a Java value class is to be generated is scoped within a complex type as opposed to globally, the complex class should occur as a nested class within the Java value class representing the complex type scope. The schema customization <jaxb:globalBindings localScoping=”toplevel”/>, specified in Section Usage, disables the generation of schema-derived nested classes and all classes are generated as toplevel classes.
The absolute class name is PackageName.[OuterClassNames.]Name.
Note: The OuterClassNames is null if the class is a top-level class. -
A base class that this class extends. See Complex Type Definition for further details.
-
A set of Java properties providing access and modification to the complex type definition’s attributes and content model represented by the value class.
-
Class-level javadoc is a combination of a documentation annotation from the schema component and/or javadoc specified within customization.
-
Creation
-
A value class supports creation via a public constructor, either an explicit one or the default no-arg constructor.
-
A factory method in the package’s
ObjectFactory
class (introduced in Java Package). The factory method returns the type of the Java value class. The name of the factory method is generated by concatenating the following components:-
The string constant
create
. -
If the Java value class is nested within another value class, then the concatenation of all outer Java class names.
-
The name of the Java value class.
For example, a Java value class named
Foo
that is nested within Java value classBar
would have the following factory method signature generated in the containing Java package’sObjectFactory
class:Bar.Foo createBarFoo() {...}
-
-
5.4.2. Java Content Interface
This binding is similar to the value class binding with the following differences.
-
A content interface is a public interface while a value class is a public class.
-
A content interface can only be created with an ObjectFactory method whereas a value class can be created using a public constructor. The factory method signature is the same for both value class and content interface binding to ease switching between the two binding styles.
-
A content interface contains the method signatures for the set of properties it contains, while a value class contains method implementations.
5.5. Properties
The schema compiler binds local schema components to properties within a Java value class.
A property is defined by:
-
A name, which is either computed from the XML name or specified by a binding customization for the schema component.
-
A base type, which may be a Java primitive type (e.g.,
int
) or a reference type. -
An optional predicate , which is a mechanism that tests values of the base type for validity and throws a
TypeConstraintException
if a type constraint expressed in the source schema is violated.[6] -
An optional collection type , which is used for properties whose values may be composed of more than one value.
-
A default value . Schema component has a schema specified default value which is used when property’s value is not set and not nil.
-
Is nillable . A property is nillable when it represents a nillable element declaration.
A property is realized by a set of access methods. Several property models are identified in the following subsections; each adds additional functionally to the basic set of access methods.
A property’s access methods are named in the
standard JavaBeans style: the name-mapping algorithm is applied to the
property name and then each method name is constructed by prefixing the
appropriate verb (get
, set
, etc.).
A property is said to have a set value if that value was assigned to it during unmarshalling[7] or by invoking its mutation method. The value of a property is its set value, if defined; otherwise, it is the property’s schema specified default value, if any; otherwise, it is the default initial value for the property’s base type as it would be assigned for an uninitialized field within a Java class[8]. States of a Property Value illustrates the states of a JAXB property and the invocations that result in state changes.
5.5.1. Simple Property
A non-collection property prop
with a base
type Type is realized by the two methods
public Type getId();
public void setId(Type value);
where Id is a metavariable that represents
the Java method identifier computed by applying the name mapping
algorithm described in The Name to Identifier Mapping Algorithm
to prop. There is one exception to this
general rule in order to support the boolean property described in
[BEANS]. When Type is boolean, the getId
method specified above is
replaced by the method signature, boolean isId()
.
-
The
get
oris
method returns the property’s value as specified in the previous subsection. If null is returned, the property is considered to be absent from the XML content that it represents. -
The
set
method defines the property’s set value to be the argumentvalue
. If the argument value isnull
, the property’s set value is discarded. Prior to setting the property’s value when TypeConstraint validation is enabled[9], a non-null
value is validated by applying the property’s predicate. IfTypeConstraintException
is thrown, the property retains the value it had prior to theset
method invocation.
When the base type for a property is a
primitive non-reference type and the property’s value is optional, the
corresponding Java wrapper class can be used as the base type to enable
discarding the property’s set value by invoking the set method with a
null parameter. isSet
Property Modifier describes an alternative to using a wrapper class for this
purpose. The [jaxb:globalBinding] customization @optionalProperty
controls the binding of an optional primitive property as described in
Usage.
Example:
In the purchase order schema, the partNum
attribute of the item element definition is declared:
<xs:attribute name="partNum" type="SKU" use="required"/>
This element declaration is bound to a simple
property with the base type java.lang.String
:
public String getPartNum();
public void setPartNum(String x);
The setPartNum
method could apply a
predicate to its argument to ensure that the new value is legal, i.e.,
that it is a string value that complies with the constraints for the
simple type definition, SKU, and that derives by restriction from
xs:string
and restricts the string value to match the regular
expression pattern "\d{3}-[A-Z]{2}"
.
It is legal to pass null
to the
setPartNum
method even though the partNum
attribute declaration’s
attribute use
is specified as required. The determination if partNum
content actually has a value is a local structural constraint rather
than a type constraint, so it is checked during validation rather than
during mutation.
5.5.2. Collection Property
A collection property may take the form of an indexed property or a list property. The base type of an indexed property may be either a primitive type or a reference type, while that of a list property must be a reference type.
A collection consists of a group of
collection items. If one of the collection items can represent a
nillable element declaration, setting a collection item to null
is
semantically equivalent to inserting a nil element, xsi:nil="true"
,
into the collection property. If none of the collection items can ever
represent a nillable element declaration, setting a collection item to
null
is the semantic equivalent of removing an optional element from
the collection property.
5.5.2.1. Indexed Property
This property follows the indexed property
design pattern for a multi-valued property from the JavaBean
specification. An indexed property prop
with base type Type is
realized by the five methods
public Type[] getId();
public void setId(Type[] value);
public void setId(int index, Type value);
public Type getId(int index);
public int getIdLength();
regardless of whether Type is a primitive
type or a reference type. Id is computed from prop
as it was defined
in simple property. An array item is a specialization of the collection
item abstraction introduced in the collection property overview.
-
getId()
The arraygetter
method returns an array containing the property’s value. If the property’s value has not set, thennull
is returned. -
setId(Type [])
Thearray setter
method defines the property’s set value. If the argument itself isnull
then the property’s set value, if any, is discarded. If the argument is notnull
andTypeConstraint
validation is enabled[6] then the sequence of values in the array are first validated by applying the property’s predicate, which may throw aTypeConstraintException
. If theTypeConstraintException
is thrown, the property retains the value it had prior to theset
method invocation. The property’s value is only modified after theTypeConstraint
validation step. -
setId(int, Type)
The indexedsetter
method allows one to set a value within the array. The runtime exceptionjava.lang.ArrayIndexOutOfBoundsException
may be thrown if the index is used outside the current array bounds. If the value argument is non-null and TypeConstraint validation is enabled[6], the value is validated against the property’s predicate, which may throw an uncheckedTypeConstraintException
. IfTypeConstraintException
is thrown, the array index remains set to the same value it had before the invocation of the indexedsetter
method. When the array item represents a nillable element declaration and the indexed setter value parameter is null, it is semantically equivalent to inserting a nil element into the array. -
getId(int)
The indexedgetter
method returns a single element from the array. The runtime exceptionjava.lang.ArrayIndexOutOfBoundsException
may be thrown if the index is used outside the current array bounds. In order to change the size of the array, you must use the array set method to set a new (or updated) array. -
getIdLength()
The indexed length method returns the length of the array. This method enables you to iterate over all the items within the indexed property using the indexed mutators exclusively. Exclusive use of indexed mutators and this method enable you to avoid the allocation overhead associated with arraygetter
andsetter
methods.
The arrays returned and taken by these
methods are not part of the content object’s state. When an array
getter
method is invoked, it creates a new array to hold the returned
values. Similarly, when the corresponding array setter
method is
invoked, it copies the values from the argument array.
To test whether an indexed property has a set
value, invoke its array getter
method and check that the result is not
null
. To discard an indexed property’s set value, invoke its array
setter
method with an argument of null
.
See the customization attribute
collectionType
in <globalBindings>
Declaration
and <property>
Declaration on how to enable the generation of indexed property
methods for a collection property.
Example:
In the purchase order schema, we have the
following repeating element occurrence of element item within
complexType
Items.
<xs:complexType name="Items">
<xs:sequence>
<xs:element name="item" minOccurs="1" maxOccurs="unbounded">
<xs:complexType>...</xs:complexType>
</xs:element>
</xs:complexType>
The content specification of this element type could be bound to an array property realized by these five methods:
public Items.ItemType[] getItem();
public void setItem(Items.ItemType[] value);
public void setItem(int index, Items.ItemType value);
public Items.ItemType getItem(int index);
public int getItemLength();
5.5.2.2. List Property
A list property prop
with base type Type
is realized by the method where List
public List<Type> getId();
is the interface java.util.List
,
Id is defined as above. If base type is a primitive type, the
appropriate wrapper class is used in its place.
-
The
get
method returns an object that implements theList<Type>
interface, is mutable, and contains the values of type Type that constitute the property’s value. If the property does not have a set value or a schema default value, a zero lengthjava.util.List
instance is returned.
The List
returned by the get
method is a
component of the content object’s state. Modifications made to this list
will, in effect, be modifications to the content object. If
TypeConstraint
validation is enabled, the list’s mutation methods
apply the property’s predicate to any non-null
value before adding
that value to the list or replacing an existing element’s value with
that value; the predicate may throw a TypeConstraintException
. The
collection property overview discussion on setting a collection item to
null specifies the meaning of inserting a null into a List.
The unset
method introduced in
isSet
Property Modifier enables one to
discard the set value for a List property.
Design Note
There is no setter method for a List property. The getter returns
the List by reference. An item can be added to the List returned by
the getter method using an appropriate method defined on |
Example:
The content specification of the item
element type could alternatively be bound to a list property realized by
one method:
public List<Item> getItem();
The list returned by the getItem
method
would be guaranteed only to contain instances of the Item
class. As
before, its length would be checked only during validation, since the
requirement that there be at least one item
in an element instance of
complex type definition Items
is a structural constraint rather than a
type constraint.
5.5.3. Constant Property
An attribute use named prop with a schema
specified fixed value can be bound to a Java constant value. Id is
computed from prop as it was defined in simple property. The value of
the fixed attribute of the attribute use provides the <fixedValue>
constant value.
public static final Type ID = <fixedValue>;
The binding customization attribute
fixedAttributeToConstantProperty
enables this binding style.
<globalBindings>
Declaration and <property>
Declaration
describe how to use this attribute.
5.5.4. isSet
Property Modifier
This optional modifier augments a modifiable
property to enable the manipulation of the property’s value as
a set value or a defaulted value. Since this functionality
is above and beyond the typical JavaBean pattern for a property,
the method(s) associated with this modifier are not generated by default.
Customizing XML Schema to Java Representation Binding
describes how to enable this customization
using the generateIsSetMethod
attribute.
The method signatures for the isSet
property modifier are the following:
public boolean isSetId();
where Id
is defined as it was for simple and collection property.
-
The
isSet
method returnstrue
if the property has been set during unmarshalling or by invocation of the mutation methodsetId
with a non-null
value.[10]
To aid the understanding of whatisSet
method implies, note that the unmarshalling process only unmarshals set values into XML content.
A list property and a simple property with a non-reference base type require an additional method to enable you to discard the set value for a property:
public void unsetId();
-
The
unset
method marks the property as having no set value. A subsequent call togetId
method returns the schema-specified default if it existed; otherwise, it returns the Java default initial value forType
.
All other property kinds rely on the invocation of their set method with a value of null to discard the set value of its property. Since this is not possible for primitive types or a List property, the additional method is generated for these cases illustrate the method invocations that result in transitions between the possible states of a JAXB property value.
Example:
In the purchase order schema, the partNum
attribute of the element item
’s anonymous complex type is declared:
<xs:attribute name="partNum" type = "SKU" use="required"/>
This attribute could be bound to a isSet
simple property realized by these four methods:
public String getPartNum();
public void setPartNum(String skuValue);
public boolean isSetPartNum();
public void unsetPartNum();
It is legal to invoke the unsetPartNum
method even though the attribute’s use
is "required"
in the XML
Schema. That the attribute actually has a value is a local structural
constraint rather than a type constraint, so it is checked during
validation rather than during mutation.
5.5.5. Element Property
This property pattern enables the dynamic association of an element name for a JAXB property. Typically, the element name is statically associated with a JAXB property based on the schema’s element name. Element substitution groups and wildcard content allow an XML document author to use Element names that were not statically specified in the content model of the schema. To support these extensibility features, an application uses element property setters/getters to dynamically introduce element names at runtime.
The method signatures for the Element
property pattern are the following:
public void setId(JAXBElement<? extends Type> value);
public JAXBElement<? extends Type> getId();
where Id
and Type
are defined as they
were for simple and collection property. The fully qualified Java name
for JAXBElement<T>
is jakarta.xml.bind.JAXBElement<T>
. The generic
types in the method signatures are expressed as a bounded wildcard to
support element substitution group, see details in
Element Declaration.
5.5.6. Property Summary
The following core properties have been defined:
-
Simple property - JavaBean design pattern for single value property
-
Indexed property - JavaBean design pattern for multi-valued property
-
List property - Leverages java.util.Collection
-
Constant property
The methods generated for these four core
property kinds are sufficient for most applications. Configuration-level
binding schema declarations enable an application to request finer
control than provided by the core properties. For example, the isSet
property modifier enables an application to determine if a property’s
value is set or not.
5.6. Java Element Representation
Based on rationale and criteria described in
Element Declaration, the schema
compiler binds an element declaration to a Java instance that implements
jakarta.xml.bind.JAXBElement<T>
. JAXBElement<T>
class provides access
to the basic properties of an XML element: its name, the value of the
element’s datatype, and whether the element’s content model is set to
nil, i.e. xsi:nil="true"
. Optional properties for an Xml element that
corresponds to an element declaration from a known schema include the
element declaration’s declared type and scope.
The enhanced, default binding for an element declaration only generates a element instance factory method and is described in Named Java Element instance.[11] The customized binding that generates a schema-dervied Element class for an element declaration is described in Java Element Class.
5.6.1. Named Java Element instance
Based on the normative binding details described in Bind to JAXBElement<T> Instance, the schema compiler binds an element declaration to an element instance factory method.
The following is a generic element factory signature.
package elementDeclarationTargetNamespace;
class ObjectFactory {
jakarta.xml.bind.JAXBElement<ElementType>
createElementName(ElementType value);
}
The element factory method enables an
application to work with elements without having to directly know the
precise javax.xml.namespace.QName
. The element factory method
abstraction sets the Xml element name with the Java representation of
the element, thus shielding the JAXB user from the complexities of
manipulating namespaces and QNames.
<xs:schema targetNamespace=”a” xmlns:a=”a”/>
<xs:element name=”Foo” type=”xsd:int”/>
class ObjectFactory {
// returns JAXBElement with its name set to QName(“a”, “Foo”).
JAXBElement<Integer> createFoo(Integer value);
}
5.6.2. Java Element Class
Based on criteria to be identified in Bind to Element Class, the schema compiler binds an element declaration to a Java element class. An element class is defined in terms of the properties of the Element Declaration Schema Component as follows:
-
An element class name is generated from the element declaration’s name using the XML Name to Java identifier name mapping algorithm specified in The Name to Identifier Mapping Algorithm.
-
Scope of element class
-
Global element declarations are declared in package scope.
-
By default, local element declarations occur in the scope of the first ancestor complex type definition that contains the declaration. The schema customization <jaxb:globalBindings localScoping=”toplevel”/>, specified in Usage, disables the generation of schema-derived nested classes and all classes are generated as toplevel classes.
-
-
Each generated Element class must extend the Java class
jakarta.xml.bind.JAXBElement<T>
. The type T of theJAXBElement<T>
is derived from the element declaration’s type. Anonymous type definition binding is a special case that is specified in Binding of an anonymous complex type definition. -
A factory method is generated in the package’s
ObjectFactory
class introduced in Java Package. The factory method returnsJAXBElement<T>
. The factory method has one parameter that is of typeT
. The name of the factory method is generated by concatenating the following components:-
The string constant
create
. -
If the Java element class is nested within a value class, then the concatenation of all outer Java class names.
-
The name of the Java value class.
The returned instance has the Xml Element name property set to the QName representing the element declaration’s name.
For example, a Java element class namedFoo
that is nested within Java value classBar
would have the following factory method generated in the containing Java package’sObjectFactory
class:JAXBElement<Integer> createBarFoo(Integer value)
-
-
A public no-arg constructor is generated.
The constructor must set the appropriate Xml element name, just as the element factory method does. -
The Java element representation extends
JAXBElement<T>
class, its properties provide the capability to manipulate-
the value of the element’s content
Xml Schema’s type substitution capability is enabled by this property. -
whether the element’s content model is
nil
-
<xs:complexType name="AComplexType" mixed="true">
<xs:sequence>
<xs:element name="ASimpleElement" type="xs:int"/>
</xs:sequence>
</xs:complexType>
Its Java representation:
public value class AComplexType {
public class ASimpleElement extends
jakarta.xml.bind.JAXBElement<Integer> {
}
...
};
class ObjectFactory {
AComplexType createAComplexType();
JAXBElement<Integer>
createAComplexTypeASimpleElement(Integer value);
...
}
5.6.3. Java Element Representation Summary
Element declaration binding evolved inJakarta XML Binding to support XML Schema type substitution. The following diagrams illustrate the binding changes for the following schema fragment:
<xs:element name=”foo” type=”fooType”/>
While a JAXB 1.0 Element interface implemented its type’s interface,
a Jakarta XML Binding Element instance has a
composition relationship to the value of the element declaration’s type,
accessible via the jakarta.xml.bind.JAXBElement<T>
property Value
.
This change reflects the relationship that type substitution allows an
element declaration to be associated with many different datatypes, not
just the datatype that was defined statically within the schema.
An added benefit to the default binding change is to reduce the overhead associated with always generating Java Element classes for every global element declaration. A value class is generated for every complex type definition and only a factory method needs to be generated for each global element declaration.
5.7. Summary
The composition and relationships between the Java components introduced in this section are reflected in the following diagram.
6. Binding XML Schema to Java Representations
This chapter describes binding of XML schema components to Java representations. The default binding is identified in this chapter and the next chapter specifies the customizations that override default binding.
6.1. Overview
The abstract model described in [XSD Part 1] is used to discuss the default binding of each schema component type. Each schema component is described as a list of properties and their semantics. References to properties of a schema component as defined in [XSD Part 1] are denoted using the notation {schema property} throughout this section. References to properties of information items as defined in [XML-Infoset] are denoted by the notation [property].
All JAXB implementations are required to implement the default bindings specified in this chapter. However, users and JAXB implementors can use the global configuration capabilities of the custom binding mechanism to override the defaults in a portable manner.
For each binding of a schema component to its Java representation, there is a description of Java mapping annotation(s), described in Java Types To XML, to be generated with the Java representation. The standardization of these mapping annotations assist in specifying the portability of a schema-derived JAXB-annotated classes. All JAXB implementations are required to be able to unmarshal/marshal another implementation’s schema-derived Java value classes by interpreting the specified mapping annotations. Note that each mapping annotation is described independent of whether it is the default mapping or a customized mapping, JAXB implementations are allowed to optimize away redundant mapping annotations that are the default mapping annotation.
Design Note
Note that the mapping annotations generated on the schema derived classes do not capture all aspects from the original schema. A schema generated from the mapping annotations of the schema derived classes differs from the original schema used to generate the schema-derived classes. The original schema is more precise for validation purposes than the one generated from the schema-derived classes. |
All examples are non-normative. Note that in the examples, the schema-derived code does not list all required mapping annotations. In the interest of being terse, only the mapping annotations directly connected to the schema component being discussed are listed in its example.
6.2. Simple Type Definition
A schema component using a simple type definition typically binds to a Java property. Since there are different kinds of such schema components, the following Java property attributes (common to the schema components) are specified here and include:
-
base type
-
collection type if any
-
predicate
The rest of the Java property attributes are specified in the schema component using the simple type definition.
While not necessary to perform by default,
this section illustrates how a simple type definition is bound to a JAXB
mapped class. This binding is necessary to preserve a simple type
definition referred to by xsi:type
attribute in an Xml instance
document. See Usage for the
customization that enables this binding.
6.2.1. Type Categorization
The simple type definitions can be categorized as:
-
schema built-in datatypes [XSD PART2]
-
user-derived datatypes
Conceptually, there is no difference between the two. A schema built-in datatype can be a primitive datatype. But it can also, like a user-derived datatype, be derived from a schema built-in datatype. Hence no distinction is made between the schema built-in and user-derived datatypes.
The specification of simple type definitions is based on the abstract model described in Section 4.1, “Simple Type Definition” [XSD PART2]. The abstract model defines three varieties of simple type definitions: atomic, list, union. The Java property attributes for each of these are described next.
6.2.2. Atomic Datatype
If an atomic datatype has been derived by restriction using an “enumeration” facet, the Java property attributes are defined by Enum Type. Otherwise they are defined as described here.
The base type is derived upon the XML built-in type hierarchy [XSD PART2, Section 3] reproduced below.
The above diagram is the same as the one in [XSD PART2] except for the following:
-
Only schema built-in atomic datatypes derived by restriction have been shown.
-
The schema built-in atomic datatypes have been annotated with Java data types from the Java Mapping for XML Schema Built-in Types table below.
Design Note
xs:anyURI is not bound to java.net.URI by default since not all
possible values of xs:anyURI can be passed to the java.net.URI constructor.
Using a global JAXB customization described in |
The following is a mapping for subset of the XML schema built-in data types to Java data types. This table is used to specify the base type later.
XML Schema Datatype | Java Datatype |
---|---|
xsd:string |
java.lang.String |
xsd:integer |
java.math.BigInteger |
xsd:int |
int |
xsd:long |
long |
xsd:short |
short |
xsd:decimal |
java.math.BigDecimal |
xsd:float |
float |
xsd:double |
double |
xsd:boolean |
boolean |
xsd:byte |
byte |
xsd:QName |
javax.xml.namespace.QName [15] |
xsd:dateTime |
javax.xml.datatype.XMLGregorianCalendar [15] |
xsd:base64Binary |
byte[] |
xsd:hexBinary |
byte[] |
xsd:unsignedInt |
long |
xsd:unsignedShort |
int |
xsd:unsignedByte |
short |
xsd:time |
javax.xml.datatype.XMLGregorianCalendar [15] |
xsd:date |
javax.xml.datatype.XMLGregorianCalendar [15] |
xsd:g* |
javax.xml.datatype.XMLGregorianCalendar [15] |
xsd:anySimpleType |
java.lang.Object |
xsd:anySimpleType |
java.lang.String |
xsd:duration |
javax.xml.datatype.Duration [15] |
xsd:NOTATION |
javax.xml.namespace.QName [15] |
The base type is determined as follows:
-
Map by value space bounding facets
If the simple type derives from or isxsd:integer
and has either a constraining lower and/or upper bounds facet(s) or totalDigits facet, check if the following optimized binding is possible:-
If the simple type derives from or is
xsd:short
,xsd:byte
orxsd:unsignedByte
, go to step 2. -
If the value space for the simple type is representable in the range of
java.lang.Integer.MIN_VALUE
andjava.lang.Integer.MAX_VALUE
, map to java primitive type,int
. -
If the value space for the simple type is representable in the range of
java.lang.Long.MIN_VALUE
andjava.lang.Long.MAX_VALUE
, map to java primitive type,long
. -
Else go to step 2.
-
-
Map by datatype
If a mapping is defined for the simple type in Table 6.1, the base type defaults to its defined Java datatype. -
Map by base datatype
Otherwise, the base type must be the result obtained by repeating the step 1 and 2 using the {base type definition}. For schema datatypes derived by restriction, the {base type definition} represents the simple type definition from which it is derived. Therefore, repeating step 1 with {base type definition} essentially walks up the XML Schema built-in type hierarchy until a simple type definition which is mapped to a Java datatype is found.
The Java property predicate must be as specified in “Simple Type Definition Validation Rules,” Section 4.1.4[XSD PART2].
Example:
The following schema fragment (taken from
Section 4.3.1, “Length” [XSD PART2]):
<xs:simpleType name="productCode">
<xs:restriction base="xs:string">
<xs:length value="8" fixed="true"/>
</xs:restriction>
</xs:simpleType>
The facet “length” constrains the length of a
product code (represented by productCode
) to 8 characters (see
section 4.3.1 [XSD PART2] for details).
The Java property attributes corresponding to the above schema fragment are:
-
There is no Java datatype mapping for
productCode
. So the Java datatype is determined by walking up the built-in type hierarchy. -
The
{base type definition}
ofproductCode
isxs:string
.xs:string
is mapped tojava.lang.String
(as indicated in the table, and assuming no customization). Therefore,productCode
is mapped to the Java datatypejava.lang.String
. -
The predicate enforces the constraints on the length.
6.2.2.1. Notation
Given that the value space of xsd:NOTATION
is the set of xsd:QName
, bind xsd:NOTATION
type to
javax.xml.namespace.QName
.
For example, the following schema:
<xs:schema targetNamespace="http://e.org" xmlns:e="http://e.org"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:notation name="jpeg" public="image/jpeg" system="jpeg.exe"/>
<xs:notation name="png" public="image/png" system="png.exe"/>
<xs:simpleType name="pictureType">
<xs:restriction base="xs:NOTATION">
<xs:enumeration value="e:jpeg"/>
<xs:enumeration value="e:png"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="Picture">
<xs:simpleContent>
<xs:extension base="xs:hexBinary">
<xs:attribute name="format" type="e:pictureType"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:schema>
is mapped to the following Java code:
package org.e;
import javax.xml.namespace.QName;
public class Picture {
void setValue(byte[] value) {...}
byte[] getValue() {...}
void setFormat(QName value)\{...}
QName getFormat() {...}
}
With the following usage scenario:
Picture pic = ...;
pic.setFormat(new QName("http://e.org","jpeg"));
6.2.2.2. Bind to a JAXB mapped class
By default, a named simple type definition is
not bound to a Java class. This binding is only necessary to enable the
precise type of an xsi:type
substitution to be preserved as described
in Type Substitution of a Simple Type Definition.
This binding is enabled via the global binding
customization attribute @mapSimpleTypeDef specified in
Usage.
The binding of a named simple type definition
to a Java value class is based on the abstract model properties in
Simple Type Definition Schema Component.
The Java value class must be defined as specified here,
unless the ref attribute is specified on the <jaxb:class>
declaration,
in which case the schema compiler will simply assume that the nominated
class is already bound to this simple type.
-
name: name is the Java identifier obtained by mapping the XML name {name} using the name mapping algorithm, specified in The Name to Identifier Mapping Algorithm. Note that anonymous simple type definition’s are never bound to a Java value class.
-
package: The schema-derived Java value class is generated into the Java package that represents the binding of {target namespace}
-
outer class name: There is no outer class name for a global simple type definition.
-
base class: Due to a constraint specified for @XmlValue in Section 8, this class can not extend any other class. The derivation by restriction hierarchy for simple type definitions can not be captured in the schema-derived Java value class.
-
value property: Same as the binding of simple content in Simple Content Binding to an @XmlValue annotated JAXB property.
The next two examples illustrate the binding of a simple type definition to a Java value class when the appropriate JAXB schema customization is enabled.
<xs:simpleType name="productCode">
<xs:restriction base="xs:string">
<xs:length value="8" fixed="true"/>
</xs:restriction>
</xs:simpleType>
@XmlType(name="productCode")
public class ProductCode {
@XmlValue
String getValue();
void setValue(String value);
}
6.2.2.3. Annotations for standard XML datatypes
By default, a schema-derived JAXB property bound from one of the following standard XML datatypes is annotated with the specified mapping annotation.
Schema Type |
JAXB Property Annotation |
---|---|
|
|
|
|
|
|
Note that JAXB schema customizations could override these default binding.
6.2.3. Enum Type
The default mapping for a named atomic type
that is derived by restriction with enumeration facet(s) and whose
restriction base type (represented by {base type definition}) is
xs:String
[17] or derived from it is mapped to an
enum type. The [typesafeEnumBase] attribute customization described in
<globalBindings>
Declaration, enables
global configuration to alter what Xml built-in datatypes are bound by
default to an enum type. An anonymous simple type definition is never
bound to an enum class by default, but it can be customized as described
in <typesafeEnum>
Declaration to bind to an enum type.
6.2.3.1. Example binding
An example is provided first followed by a more formal specification.
XML Schema fragment:
<xs:simpleType name="USState">
<xs:restriction base="xs:NCName">
<xs:enumeration value="AK"/>
<xs:enumeration value="AL"/>
</xs:restriction>
</xs:simpleType>
The corresponding enum type binding is:
public enum USState {
AK, AL;
public String value() { return name(); }
public static USState fromValue(String value) {...}
};
6.2.3.2. Enum type binding
The characteristics of an enum type are derived in terms of the properties of the Simple Type Definition Schema Component as follows:
The enum type binding is defined as follows:
-
name: The default name of the enum type, enumType, is computed by applying the XML Name to Java identifier mapping algorithm to the {name} of the simple type definition. There is no mechanism to derive a name for an anonymous simple type definition, the customization must provide the name.
-
package name: The package name is determined from the {targetnamespace} of the schema that directly contains the simple type definition.
-
outer class name:
-
There is no outer class name for a global simple type definition.
-
There is no outer class name when schema customization, [jaxb:globalBindings] @localScoping , specified in Section Usage, has a value of toplevel.
-
The outer class name for an anonymous simple type definition is computed by traversing up the anonymous simple type definition’s ancestor tree until the first ancestor is found that is:
-
an XML component that is mapped to a Java value class, the outer class name is composed of the concatenation of this Java value class’s outer class name, ".", and its name.
-
a global declaration or definition is reached. There is no outer class name for this case.
-
-
-
enum constants: Specified in next section.
Note that since a Java enum type is essentially a final class, it is not possible for it to be subclassed. Thus, any derivations of a simple type definition bound to an enum type can not be captured by an equivalent Java inheritance relationship.
The schema-derived enum is annotated, either explicitly or by default mapping annotations, with the mapping annotation @XmlEnum, specified in Section 8. The @XmlEnum annotation elements are derived in terms of the abstract model properties for a simple type definition summarized in Simple Type Definition Schema Component as follows:
@XmlEnum element | @XmlEnum value |
---|---|
name |
simple type definition’s {name} |
namespace |
{target namespace} |
value |
the java type binding of the simple type definition’s {base type definition} |
6.2.3.3. Enum Constant
An enum constant is derived for each enumeration facet of the atomic type definition. The characteristics of an enum constant of the enum type are derived in terms of the properties of the Enumeration Facet Schema Component as follows:
-
name: The name is either specified via customization,
jaxb:typesafeEnumMember
described in Usage, or the name is computed as specified in XML Enumvalue-to-Java Identifier Mapping. -
type: The Java type binding of the simple type definition’s {base_type_definition}.
-
value : The conversion of string {value} to type. Value is manipulated via the following generated enum type methods:
public type value(); public static enumTypeName fromValue(type value);
To assist an application in manipulating the
enum constants that comprise an enum type, all enum types have the
following two implicitly declared static methods as specified in Section
8.9 in [JLS3]. The enum type’s static method values()
returns an array
of all enum constants. The static method valueOf(String name)
returns
the enum constant represented by the name parameter.
6.2.3.4. XML Enumvalue-to-Java Identifier Mapping
The default name for the enum constant is based on mapping of the XML enumeration value to a Java identifier as described below.
The XML enumeration value {value} is mapped to a Java Identifier using the algorithm specified in Deriving a legal Java identifier from an enum facet value. If there is a collision among the generated constant fields name or if it is not possible to generate a legal Java identifier for one or more of the generated constant field names, see @typesafeEnumMemberName for customization options to resolve this error case.
6.2.3.5. Enum Constant Name differs from its Value
For all cases where there exist at least one enumeration constant name that is not the same as the enumeration constant’s value, the generated enum type must have a final value field that is set by the enum type’s constructor. The code generation template is the following:
public enum enumType {
EnumConstantName1(EnumConstantValue1),
...
EnumConstantNameX(EnumConstantValueX);
public EnumConstantValueType value() { return value; }
public static enumType fromValue(EnumConstantValueType val)
{...}
final private EnumConstantValueType value;
private enumType(EnumConstantValueType value) {
this.value = value;
}
}
public enum enumType {
EnumConstantName1, ..., EnumConstantNameX;
public String[18] value() { return name(); }
public static enumType fromValue(String value) {...}
}
The schema-derived enum constant is
annotated, either explicitly or by default mapping annotations, with the
mapping annotation specified in Section 8. The @XmlEnumValue
annotation elements are derived in terms of the abstract model
properties for a enumerated facet summarized in
Enumeration Facet Schema Component as
follows:
@XmlEnumValue element | @XmlEnumValue value |
---|---|
value |
Enumeration facet’s {value} |
Given following schema fragment:
<xs:simpleType name="Coin">
<!-- Assume jaxb customization that binds Coin to an enumType -->
<xs:restriction base="xs:int"> +
<!-- Assume jaxb customization specifying enumConstantName -->
<xs:enumeration value="1"/> <!-- name="penny"-->
<xs:enumeration value="5"/> <!-- name="nickel"-->
<xs:enumeration value="10"/><!-- name="dime"-->
<xs:enumeration value="25"/><!-- name="quarter-->
</xs:restriction>
</xs:simpleType>
Schema-derived enum type:
@XmlEnum(value="java.lang.Integer.class")
public enum Coin {
@XmlEnumValue("1") PENNY(1),
@XmlEnumValue("5") NICKEL(5),
@XmlEnumValue("10") DIME(10),
@XmlEnumValue("25") QUARTER(25);
public int value() { return value; }
public static Coin fromValue(int value) {...}
private final Integer value;
Coin(int value) { this.value = value; }
}
6.2.4. List
A list simple type definition can only contain list items of atomic or union datatypes. The item type within the list is represented by the schema property {item type definition}.
The Java property attributes for a list simple type definition are:
-
The base type is derived from the {item type definition} as follows. If the Java datatype for {item type definition} is a Java primitive type, then the base type is the wrapper class for the Java primitive type. Otherwise, the Java datatype is derived from the XML datatype as specified in Atomic Datatype and Enum Type.
-
The collection type defaults to an implementation of
java.util.List
. Note that this specification does not specify the default implementation for the interfacejava.util.List
, it is implementation dependent. -
The predicate is derived from the “Simple Type Definition Validation Rules,” in section 4.1.4,[XSD PART2].
Example:
For the following schema fragment:
<xs:simpleType name="xs:USStateList">
<xs:list itemType="xs:string"/>
</xs:simpleType>
The corresponding Java property attributes are:
-
The base type is derived from {item type definition} which is XML datatype,
"xs:string"
, thus the Java datatype isjava.util.String
as specified in Java Mapping for XML Schema Built-in Types. -
The collection type defaults to an implementation of
java.util.List
. -
The predicate only allows instances of base type to be inserted into the list. When failfast check is being performed[19], the list’s mutation methods apply the property’s predicate to any non-
null
value before adding that value to the list or replacing an existing element’s value with that value; the predicate may throw aTypeConstraintException
.
The schema-derived property is annotated, either explicitly or by default mapping annotations, with the mapping annotation @XmlList, specified in Section 8.
6.2.5. Union Property
A union property prop is used to bind a union simple type definition schema component. A union simple type definition schema component consists of union members which are schema datatypes. A union property, is therefore, realized by:
public Type getId();
public void setId(Type value);
where Id
is a metavariable that represents
the Java method identifier computed by applying the name mapping
algorithm described in The Name to Identifier Mapping Algorithm to prop .
The base type is String. If one of the
member types is derived by list, then the Union property is represented
as the appropriate collection property as specified by the customization
<jaxb:globalBindings>
@collectionType value, specified in
Usage.
-
The
getId
method returns the set value. If the property has no set value then the valuenull
is returned. The value returned is Type. -
The
setId
method sets the set value.
If value isnull
, the property’s set value is discarded. Prior to setting the property’s value when TypeConstraint validation is enabled, a non-null
value is validated by applying the property’s predicate, which may throw aTypeConstraintException
. No setter is generated if the union is represented as a collection property.
Example: Default Binding: Union
The following schema fragment:
<xs:complexType name="CTType">
<xs:attribute name="state" type="ZipOrName"/>
</xs:complexType>
<xs:simpleType name="ZipOrName"
memberTypes="xs:integer xs:string"/>
is bound to the following Java representation.
public class CTType {
String getState() {...}
void setState(String value) {...}
}
6.2.6. Union
A simple type definition derived by a union is bound using the union property with the following Java property attributes:
-
the base type as specified in Union Property.
-
if one of the member types is derived by
<xs:list>
, then the union is bound as a Collection property. -
The predicate is the schema constraints specified in “Simple Type Definition Validation Rules,” Section 4.1.4 [XSD PART2].
6.3. Complex Type Definition
6.3.1. Aggregation of Java Representation
A Java representation for the entire schema is built based on aggregation. A schema component aggregates the Java representation of all the schema components that it references. This process is done until all the Java representation for the entire schema is built. Hence a general model for aggregation is specified here once and referred to in different parts of the specification.
The model assumes that there is a schema component SP which references another schema component SC. The Java representation of SP needs to aggregate the Java representation of SC. There are two possibilities:
-
SC is bound to a property set.
-
SC is bound to a Java datatype or a Java value class.
Each of these is described below.
6.3.1.1. Aggregation of Datatype/Class
If a schema component SC is bound to a Java datatype or a Java value class, then SP aggregates SC’s Java representation as a simple property defined by:
-
name: the name is the class/interface name or the Java datatype or a name determined by SP. The name of the property is therefore defined by the schema component which is performing the aggregation.
-
base type: If SC is bound to a Java datatype, the base type is the Java datatype. If SC is bound to a Java value class, then the base type is the class name, including a dot separated list of class names within which SC is nested.
-
collection type: There is no collection type.
-
predicate: There is no predicate.
6.3.1.2. Aggregation of Property Set
If SC is bound to a property set, then SP aggregates by adding SC’s property set to its own property set.
Aggregation of property sets can result in name collisions. A name collision can arise if two property names are identical. A binding compiler must generate an error on name collision. Name collisions can be resolved by using customization to change a property name.
6.3.2. Java value class
The binding of a complex type definition to a Java value class is based on the abstract model properties in Complex Type Definition Schema Component. The Java value class must be defined as specified here, unless the ref attribute is specified on the <jaxb:class> customization, in which case the schema compiler will simply assume that the nominated class is already bound to this complex type.[20]
-
name: name is the Java identifier obtained by mapping the XML name {name} using the name mapping algorithm, specified in The Name to Identifier Mapping Algorithm. For the handling of an anonymous complex type definition, see Binding of an anonymous complex type definition for how a name value is derived from its parent element declaration.
-
package:
-
For a global complex type definition, the derived Java value class is generated into the Java package that represents the binding of {target namespace}
-
For the value of package for an anonymous complex type definition, see Binding of an anonymous complex type definition.
-
-
outer class name:
-
There is no outer class name for a global complex type definition.
-
Binding of an anonymous complex type definition defines how to derive this property from the element declaration that contains the anonymous complex type definition.
-
-
base class: A complex type definition can derive by restriction or extension (i.e. {derivation method} is either "extension" or "restriction"). However, since there is no concept in Java programming similar to restriction, both are handled the same. If the {base type definition} is itself mapped to a Java value class (Ci2), then the base class must be Ci2. This must be realized as:
public class Ci1 extends Ci2 { ..... }
See example of derivation by extension at the end of this section.
-
abstract: The generated Java class is abstract when the complex type definition’s {abstract} property is
true
. -
property set: The Java representation of each of the following must be aggregated into Java value class’s property set (Aggregation of Java Representation).
-
A subset of {attribute uses} is constructed. The subset must include the schema attributes corresponding to the
<xs:attribute>
children and the {attribute uses} of the schema attribute groups resolved by the <ref> attribute. Every attribute’s Java representation (Attribute use) in the set of attributes computed above must be aggregated. -
If the optional {attribute wildcard} is present, either directly or indirectly, a property defined by Attribute Wildcard is generated.
-
The Java representation for {content type} must be aggregated.
For a “Complex Type Definition with complex content,” the Java representation for {content type} is specified in Content Model - Particle, Model Group, Wildcard.
For a complex type definition which is a “Simple Type Definition with simple content,” the Java representation for {content type} is specified in Simple Content Binding.
-
If a complex type derives by restriction, there is no requirement that Java properties representing the attributes or elements removed by the restriction to be disabled. This is because (as noted earlier), derivation by restriction is handled the same as derivation by extension.
-
-
When the complex type definition’s {abstract} property is
false
, a factory method is generated in the package’sObjectFactory
class introduced in Java Package. The factory method returns the type of the Java value class. The name of the factory method is generated by concatenating the following components:-
The string constant
create
. -
The name of the Java value class.
-
The schema-derived Java value class is annotated, either explicitly or by default mapping annotations, with the mapping annotation @XmlType, specified in @XmlType. The @XmlType annotation elements are derived in terms of the abstract model properties for a complex type definition summarized in Complex Type Definition Schema Component as follows:
@XmlType element | @XmlType value |
---|---|
name |
complex type definition’s {name} |
namespace |
{target namespace} |
propOrder a |
When \{content type} is element-only
{content model} and top-level {compositor} is xs:sequence, ordered
list of JAXB property names representing order of xs:elements in
{content model}.
All other cases do not need to set propOrder. |
Example: Complex Type: Derivation by Extension
XML Schema Fragment (from XSD PART 0 primer):
<xs:complexType name="Address">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="street" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="USAddress">
<xs:complexContent>
<xs:extension base="ipo:Address">
<xs:sequence>
<xs:element name="state" type="xs:string"/>
<xs:element name="zip" type="xs:integer"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
Default Java binding:
public class Address {
String getName() {...}
void setName(String) {...}
String getStreet() {...}
void setStreet(String) {...}
void getCity() {...}
void setCity(String) {...}
}
import java.math.BigInteger;
public class USAdress extends Address {
String getState() {...}
void setState(String) {...} {
BigInteger getZip() {...}
void setZip(BigInteger) {...}
}
class ObjectFactory {
Address createAddress() {...}
USAddress createUSAddress() {...}
}
6.3.2.1. Simple Content Binding
Binding to Property
By default, a complex type definition with simple content is bound to a Java property defined by:
-
name: The property name must be
value
. -
base type, predicate, collection type: As specified in [XSD Part 1], when a complex type has simple content, the content type ({content type}) is always a simple type schema component. And a simple type component always maps to a Java datatype (Simple Type Definition). Values of the following three properties are copied from that Java type:
-
base type
-
predicate
-
collection type
-
The schema-derived JAXB property representing simple content is annotated, either explicitly or by default mapping annotations, with the mapping annotation @XmlValue, specified in @XmlValue.
Example: Simple Content: Binding To Property
XML Schema fragment:
<xs:complexType name="internationalPrice">
<xs:simpleContent>
<xs:extension base="xs:decimal">
<xs:attribute name="currency" type="xs:string"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
Default Java binding:
class InternationalPrice {
/** Java property for simple content */
@XmlValue
java.math.BigDecimal getValue() {...}
void setValue(java.math.BigDecimal value) {...}
/** Java property for attribute */
String getCurrency() {...}
void setCurrency(String) {...}
}
6.3.3. xsd:anyType
xsd:anyType
is the root of the type
definition hierarchy for a schema. All complex type definitions in a
schema implicitly derive from xsd:anyType
. Given that the JAXB
architecture does not define a common base class for all JAXB class
bindings of complex type definitions, the only possible binding property
base type binding for xsd:anyType
is to java.lang.Object
. This
binding enables all possible type and element substitutions for an
element of type xsd:anyType
.
<xs:element name="anyContent/> <!-- @type defaults to xs:anyType -->
<xs:complexType name="base">
<xs:sequence>
<xs:element ref="anyContent/>
<xs:element name="anyContentAgain" type="xs:anyType"/>
</xs:sequence>
</xs:complexType>
public class Base {
void setAnyContent(Object obj);
Object getAnyContent();
void setAnyContentAgain(Object obj);
Object getAnyContentAgain();
}
A schema author defines an element to be of
type xs:anyType
to defer constraining an element to a particular type
to the xml document author. Through the use of xsi:type
attribute or
element substitution, an xml document author provides constraints for an
element defined as xs:anyType
. The JAXB unmarshaller is able to
unmarshal a schema defined xsd:anyType
element that has been
constrained within the xml document to an easy to access JAXB mapped
class. However, when the xml document does not constrain the
xs:anyType
element, JAXB unmarshals the unconstrained content to an
element node instance of a supported DOM API.
Type substitution is covered in more detail in Type Substitution of a Complex Type Definition and Type Substitution of a Simple Type Definition. Element substitution is covered in more detail in Bind to a Simple Element property.
6.4. Attribute Group Definition
There is no default mapping for an attribute
group definition. When an attribute group is referenced, each attribute
in the attribute group definition becomes a part of the [attribute uses]
property of the referencing complex type definition. Each attribute is
mapped to a Java property as described in
Attribute use. If the attribute group
definition contains an attribute wildcard, denoted by the
xs:anyAttribute
element, then the referencing complex type definition
will contain a property providing access to wildcard attributes as
described in Attribute Wildcard.
6.5. Model Group Definition
When a named model group definition is referenced, the JAXB property set representing its content model is aggregated into the Java value class representing the complex type definition that referenced the named model group definition as illustrated in Binding for a reference to a model group definition..
This binding style results in the same properties occurring within both Java value class’s A and C to represent the referenced Model Group B’s content model.
When a model group definition’s content model contains an XML Schema component that is to be bound to a Java value class, element class or enum type, it is desirable to only create a single Java representation, not one for each complex content that references the named model group definition. This default binding from a model group definition’s content model is defined in Deriving Class Names for Named Model Group Descendants.
To meet the Jakarta XML Binding goal of predictable unmarshalling of invalid XML content, the JAXB 1.0 customization for binding a model group to a JAXB mapped class is no longer supported. Flexible Unmarshalling details the rationale behind this change.
6.5.1. Bind to a set of properties
A non-repeating reference to a model group definition, when the particle referencing the group has {max occurs} equal to one, results in a set of content properties being generated to represent the content model. Content Model - Particle, Model Group, Wildcard describes how a content model is bound to a set of properties and has examples of the binding.
6.5.2. Bind to a list property
A reference to a model group definition from a particle with a repeating occurrence is bound by default as specified in Bind a repeating occurrence model group.
Example:
Schema fragment contains a particle that
references the model group definition has a {maxOccurs} value greater
than one.
<xs:group name="AModelGroup">
<xs:choice>
<xs:element name="A" type="xs:int"/>
<xs:element name="B" type="xs:float"/>
</xs:choice>
</xs:group>
<xs:complexType name="foo">
<xs:sequence>
<xs:group ref="AModelGroup" maxOccurs="unbounded"/>
<xs:element name="C" type="xs:float"/>
</xs:sequence>
</xs:complexType>
Derived Java representation:
public class Foo {
/** A valid general content property of AModelGroup content model.*/
@XmlElements({
@XmlElement(type=Integer.class, name="A"),
@XmlElement(type=Float.class, name="B")})
java.util.List<Object> getAModelGroup() {...}
float getC() {...}
void setC(float value) {...}
};
6.5.3. Deriving Class Names for Named Model Group Descendants
When a model group definition’s content model contains XML Schema components that need to be bound to a Java class or interface, this section describes how to derive the package and name for the Java value class, enum type or element class derived from the content model of the model group definition. The binding of XML Schema components to Java classes/interfaces is only performed once when the model group definition is processed, not each time the model group definition is referenced as is done for the property set of the model group definition.
XML Schema components occurring within a model group definition’s content model that are specified by this chapter and the customization chapter to be bound to a Java value class, interface or typesafe enum class are bound as specified with the following naming exceptions:
-
package: The element class, Java value class or typesafe enum class is bound in the Java package that represents the target namespace containing the model group definition.
-
name: The name of the interface or class is generated as previously specified with one additional step to promote uniqueness between interfaces/classes promoted from a model group definition to be bound to a top-level class within a Java package. By default, a prefix for the interface/class name is computed from the model group definition’s {name} using the XML name to Java identifier algorithm. If the schema customization [jaxb:globalBindings] @localScoping has a value of toplevel, then a prefix is not generated from the model group definition’s {name}.
For example, given a model group definition named Foo containing an element declaration named bar with an anonymous complex type definition, the anonymous complex type definition is bound to a Java value class with the name FooBar. The following figure illustrates this example.
Note that even customization specified Java
value class, interface or typesafe enum class names are prepended with
the model group definition’s name. Thus, if a model group definition
named Foo
contains an anonymous simple type definition with a typesafe
enum class customization name of Colors
, the enum type name is
FooColors
.
6.6. Attribute Declaration
An attribute declaration is bound to a Java property when it is referenced or declared, as described in Attribute use, from a complex type definition.
6.6.1. Bind global attribute to a QName Constant
To assist the dynamic access to schema-defined global attributes described in Section 6.9, “Attribute Wildcard", a global attribute declaration is bound to a JAXB QName constant, derived in terms of the properties of the “Attribute Declaration Schema Component” as follows:
-
A package name, which is either computed from the attribute declaration {target namespace} or specified by binding customization of the target namespace or a specified package name for components that are scoped to no target namespace.
-
The name of the generated constant is derived from the element declaration {name} using the XML Name to Java identifier mapping algorithm for a constant name or specified by a binding customization of the attribute’s name.
-
The QName constant is a JAXB constant property in class ObjectFactory.
-
The QName constant value is initialized using the attribute declaration’s {target namespace} and {name}.
<xs:schema targetNamespace="http://e.org" xmlns:a="http://e.org">
<xs:attribute name="isOpen" type="xs:boolean"/>
</xs:schema>
package org.e;
public class ObjectFactory {
/** <xs:attribute name="{http://e.org}isOpen" type="xs:boolean"/> */
public static final javax.xml.namespace.QName IS_OPEN =
new QName("http://e.org", "isOpen");
...
}
6.7. Element Declaration
This section describes the binding of an XML element declaration to a Java representation. For a description of how this binding has changed since the previous version, see Java Element Representation Summary. This section introduces why a JAXB technology user has to use instances of JAXB element as opposed to instances of Java datatypes or Java value class when manipulating XML content.
An XML element declaration is composed of the following key components:
-
its qualified name is {target namespace} and {name}
-
its value is an instance of the Java class binding of its {type definition}
-
whether the element’s content is {nillable}
Typically, an instance of
jakarta.xml.bind.JAXBElement<T>
, returned by an element factory method,
represents an element declaration’s key components. An instance of a
Java value class or content interface represents only the value of an
element. Commonly in JAXB binding, the Java representation of XML
content enables one to manipulate just the value of an XML element, not
an actual element instance. The binding compiler statically associates
the XML element qualified name to a content property and this
information is used at unmarshal/marshal time. For cases where the
element name can be dynamically altered at runtime, the JAXB user needs
to manipulate elements, not element values. The following schema/derived
Java code example illustrates this point.
Example:
Given the XML Schema fragment:
<xs:complexType name="chair_kind">
<xs:sequence>
<xs:element name="has_arm_rest" type="xs:boolean"/>
</xs:sequence>
</xs:complexType>
Schema-derived Java value class:
public class ChairKind {
boolean isHasArmRest() {...}
void setHasArmRest(boolean value) {...}
}
A user of the Java value class ChairKind
never has to create a Java instance that both has the value of local
element has_arm_rest
and knows that its XML element name is
has_arm_rest
. The user only provides the value of the element to the
content-property hasArmRest
. A JAXB implementation associates the
content-property hasArmRest
with XML element name has_arm_rest
when
marshalling an instance of ChairKind
.
The next schema/derived Java code example illustrates when XML element information can not be inferred by the derived Java representation of the XML content. Note that this example relies on binding described in Bind wildcard schema component.
Example:
<xs:complexType name="chair_kind">
<xs:sequence>
<xs:any/>
</xs:sequence>
</xs:complexType>
public class ChairKind {
@XmlAnyElement(lax="true")
java.lang.Object getAny() {...}
void setAny(java.lang.Object elementOrValue) {...}
}
For this example, the user can provide an
Element instance to the any
content-property that contains both the
value of an XML element and the XML element name since the XML element
name could not be statically associated with the content-property any
when the Java representation was derived from its XML Schema
representation. The XML element information is dynamically provided by
the application for this case. Content Model - Particle, Model Group, Wildcard
cover additional circumstances when one can use JAXB elements.
6.7.1. Bind to JAXBElement<T> Instance
The characteristics of the generated
ObjectFactory element factory method that returns an JAXBElement<T>
instance are derived in terms of the properties of the
Element Declaration Schema Component as follows:
-
The element factory method is generated into the
ObjectFactory
class in the Java package that represents the binding of the element declaration’s {target namespace}. -
The element factory method returns an instance of
jakarta.xml.bind.JAXBElement<T>
, whereT
is the Java value class representing the {type definition} of the element declaration. The factory method sets the element name of the returned instance to the element declaration’s fully qualified name. -
The element factory method has a single parameter that is an instance of type
T
, whereT
is the Java value class representing the {type definition} of the element declaration. -
The name of the factory method is generated by concatenating the following components:
-
The string constant
create
. -
By default, if the element declaration is nested within another XML Schema component, then the concatenation of all outer Java class names representing those XML Schema components. If the schema customization [jaxb:globalBindings] @localScoping has a value of toplevel, skip this step.
-
A name that is generated from the element declaration’s {name} using the XML Name to Java identifier name mapping algorithm specified in The Name to Identifier Mapping Algorithm.
-
-
The
JAXBElement<T>
property for nil test whether an element’s content model isxsi:nil="true"
.
For example, an element declaration named
Foo
with a type of xs:int
that is nested within the content
model of complex type definition Bar
would have the following factory
method generated in the containing Java package’s ObjectFactory
class:
JAXBElement<Integer> createBarFoo(Integer value) {...}
Default binding rules require an element declaration to be bound to element factory method under the following conditions:
-
All non-abstract, named element declarations with global {scope} are bound to an element factory method that returns an
JAXBElement<T>
instance. The rationale is that any global element declaration can occur within a wildcard context and one might want to provide element instances, not instances of the element’s type, the element’s value, for this case. -
All local element declarations, having a {scope} of a complex type definition, occurring within content that is mapped to a general content property of JAXB elements must have an element factory method generated. General content property is specified in General content property. An example of when a content model is mapped to a general content property, forcing the generation of element declarations is at Examples.
The schema-derived element factory method is
annotated, either explicitly or by default mapping annotations, with the
mapping annotation @XmlElementDecl
, specified in Section 8. The
@XmlElementDecl
annotation elements are derived in terms of the
abstract model properties for an element declaration summarized in
Element Declaration Schema Component as follows:
@XmlElementDecl element | @XmlElementDecl value |
---|---|
name |
element declaration’s {name} |
namespace |
{target namespace} |
scope |
If {scope} is global, |
substitutionHeadName |
If optional {substitution group affiliation} exists, its local name. |
substitutionHeadNamespace |
If optional {substitution group affiliation} exists, its namespace. |
The element declaration’s {type} can result in additional JAXB annotations being generated on the element instance factory. For more details, see Annotations for standard XML datatypes and @XmlList in List.
The schema-derived ObjectFactory class containing the @XmlElementDecl annotations is annotated with @XmlRegistry annotation.
6.7.2. Bind to Element Class
<class>
Declaration customization enables the binding of an element declaration
with a named type definition to a schema-derived Element class. The
characteristics of the schema-derived Element class are derived in terms
of the properties of the Element Declaration Schema Component as follows:
-
The name of the generated Java Element class is derived from the element declaration {name} using the XML Name to Java identifier mapping algorithm for class names.
-
Each generated Element class must extend the Java value class
jakarta.xml.bind.JAXBElement <T>
. The next bullet specifies the schema-derived Java class name to use for generic parameterT
. -
If the element declaration’s {type definition} is
-
Anonymous
Generic parameter
T
from the second bullet is set to the schema-derived class represented the anonymous type definition generated as specified in Section 6.7.3. -
Named
Generic parameter
T
from the second bullet is set to the Java class representing the element declaration’s {type definition}.
-
-
The
ObjectFactory
method to create an instance of name has a single parameter that is an instance of typeT
. By default, the name of the ObjectFactory method is derived by concatenating outerClassNames and name. When schema customization, [jaxb:globalBindings] @localScoping, specified in Usage, has a value of toplevel, then the outer Classnames are ommitted from the factory method name. -
If {scope} is
-
Global: The derived Element class is generated into the Java package that represents the binding of {target namespace}.
-
A Complex Type Definition: By default, the derived Element class is generated within the Java value class represented by the complex type definition value of {scope}. When @localScoping is toplevel , the derived element class is generated as a toplevel class.
-
-
The property for nil test whether element’s content model is
xsi:nil="true"
. -
Optional {value constraint} property with pair of
default
orfixed
and a value.
If a default or fixed value is specified, the data binding system must substitute the default or fixed value if an empty tag for the element declaration occurs in the XML content.
A global binding customization,
@generateElementClass, specified in <globalBindings>
Declaration
enables this binding over the default
binding specified in the previous subsection.
6.7.3. Binding of an anonymous complex type definition
An anonymous complex type definition is bound to a generated schema-derived Java value class by default.
The naming characteristics of the generated Java value class is derived in terms of the properties of the Element Declaration Schema Component as follows:
-
The name of the generated Java value class is derived from the element declaration {name} using the XML Name to Java identifier.
-
The package of the generated Java value class is the same as the package derived from the element declaration’s {target namespace}.
-
The outer class names of the generated Java value class is determined by the element declaration’s {scope}. If {scope} is:
-
Global
There is no outer class name. -
A Complex Type Definition
By default, the derived Java value class is generated nested within the Java value class represented by the complex type definition value of {scope}. The derived Java value is not generated nested when schema customization [globalBindings] has attribute @localScoping with a value of toplevel.
-
-
base class: Same as defined in Java value class.
-
property set: As defined in Java value class.
-
A type factory method is generated in the package’s
ObjectFactory
class introduced in Java Package. The factory method returns the type of the Java value class. The name of the factory method is generated by concatenating the following components:-
The string constant
create
. -
If the element declaration containing the anonymous complex type definition is nested within another complex type definition representing a value class and [globalBindings] @localScoping has a value of nested , then the concatenation of all outer Java class names. This step is skipped when @localScoping has a value of toplevel.
-
The name of the Java value class.
-
The schema-derived value class is annotated
with the mapping annotation @XmlType
, specified in
@XmlType. The @XmlType
annotation
elements are set as described in Annotate Java value class with @XmlType element-value pairs with one
exception: @XmlType.name()
is set to the empty string.
As long as the element declaration is not one
of the exception cases specified in
Bind Element Declaration to JAXBElement, the schema-derived value
class is annotated with the mapping annotation @XmlRootElement
specified in Section 8. The @XmlRootElement
annotation elements are
derived in terms of the abstract model properties for the referenced
global element declaration summarized in
Element Declaration Schema Component as follows:
@XmlRootElement element | @XmlRootElement value |
---|---|
namespace |
When element declaration {target namespace} is absent, Otherwise, set @XmlElement.namespace() to value of {target namespace}. (either a qualified local element declaration or a reference to a global element) Note: same result could be achieved with package level annotation of @XmlSchema and not setting @XmlElement.namespace. |
name |
element declaration {name} |
Example:
Given XML Schema fragment:
<xs:element name="foo">
<xs:complexType>
<xs:sequence>
<xs:element name="bar" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Derived Java code:
/* Value class representing element
declaration with an anonymous complex type definition. */
@XmlType(name="")
@XmlRootElement(namespace="", name="foo")
public class Foo {
int getBar() {...}
void setBar(int value) {...}
};
class ObjectFactory {
// type factory method
Foo createFoo() {...}
// element factory method
JAXBElement<Foo> createFoo(Foo value) {...}
}
6.7.3.1. Bind Element Declaration to JAXBElement
An element declaration with an anonymous
complex type definition is not bound to a @XmlRootElement
,annotated
schema-derived class when the element declaration is:
-
nillable
-
the head element or a member of a substitution group
-
non-global (i.e. declared within a complex type definition)
When one or more of the above conditions are
met, the schema-derived class representing the anonymous complex type
definition must not be annotated with @XmlRootElement
. Instead, an
element factory that returns JAXBElement<anonymousTypeValueClass>
may be generated as specified in Bind to JAXBElement<T> Instance.
Example:
Given XML Schema fragment:
<xs:element name="foo" nillable="true">
<xs:complexType>
<xs:sequence>
<xs:element name="bar" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Derived Java code:
/* Value class representing anonymous complex type definition. */
@XmlType(name="")
public class Foo {
int getBar() {...}
void setBar(int value) {...}
};
@XmlRegistry
class ObjectFactory {
// type factory method
Foo createFoo() {...}
// element factory method
@XmlElementDecl(name="foo", namespace="", nillable="true")
JAXBElement<Foo> createFoo(Foo value) {...}
}
6.7.4. Bind to a Property
A local element declaration is bound by default to a Java property as described in Properties. The characteristics of the Java property are derived in terms of the properties of the Element Declaration Schema Component and Particle Schema Component as follows:
-
The name of the Java property is derived from the {element declaration} property’s {name} property using the XML Name to Java Identifier mapping algorithm described in The Name to Identifier Mapping Algorithm.
-
A base type for the Java property is derived from the
{element declaration}
property’s{type definition}
property as described in binding of Simple Type Definition in Simple Type Definition. or Complex Type Definition. If the base type is initially a primitive type and this JAXB property is optional, the [jaxb:globalBinding] customization@optionalProperty
controls the binding of an optional primitive property as described in Usage. -
An optional predicate for the Java property is constructed from the
{element declaration}
property’s{type definition}
property as described in the binding of simple type definition to a Java representation. -
An optional collection type for the Java property is derived from:
-
{element declaration}
property’s{type definition}
property as described in the binding of simple type definition to a Java representation -
the
{particle}
property’s{max occurs}
value being greater than one.
-
-
Element defaulting
The default value is derived from the element declaration’s \{value constraint} property’s value. Unlike attribute defaulting, an element only defaults when there is an empty element tag in an xml document. The element’s default value is captured by mapping annotation@XmlElement.defaultValue()
. The unmarshaller sets the property to this default value when it encounters an empty element tag. The marshaller can output an empty element tag whenever the element’s@XmlValue
property value is the same as its defaulted value.. -
A local element declaration that binds to a JAXB property with a primitive base type is bound as an optional JAXB property if the element declaration is a member of a choice model group or the element declaration’s particle has optional occurrence,
{min occurs}
value is"0"
, or belongs to a model group that has optional occurrence. By default, the optional JAXB property binds the property’s base type to the Java wrapper class for the primitive type. One can test and set the absence of an optional property using null. The [jaxb:globalBinding] customization@optionalProperty
controls alternative bindings of an optional primitive property as described in Usage. -
If the element declaration’s {nillable} property is
"true"
, the base type for the Java property is mapped to the corresponding Java wrapper class for the Java primitive type. Setting the property to thenull
value indicates that the property has been set to the XML Schema concept of@xs:nil="true"
.
This Java property is a member of the Java value class that represents the binding of the complex type definition containing the local element declaration or reference to global element.
The schema-derived JAXB property getter
method is annotated, either explicitly or by default mapping
annotations, with the mapping annotation @XmlElement
, specified in
@XmlElement. The @XmlElement
annotation elements are
derived in terms of the abstract model properties for the referenced
global element declaration summarized in
Element Declaration Schema Component as follows:
@XmlElement element | @XmlElement value |
---|---|
namespace |
When element declaration {target namespace} is absent, Otherwise, set @XmlElement.namespace() to value of {target namespace}. (either a qualified local element declaration or a reference to a global element) Note: same result could be achieved with package level annotation of @XmlSchema and not setting @XmlElement.namespace. |
name |
element declaration {name} |
nillable |
element declaration {nillable} |
defaultValue |
if element declaration {value constraint} is not absent, set defaultValue() to {value constraint} ’s value. |
Xml Schema example containing an element substitution group illustrates how to define an element substitution group and to reference the head element of the substitution group within an Xml Schema. Avoid binding of Xml Schema from Xml Schema example containing an element substitution group illustrates the Java bindings of the element substation enabled schema. Element substitution using Java bindings from Avoid binding of Xml Schema from Xml Schema example containing an element substitution group demonstrates element substitution using the JAXB API. Invalid element substitution using Java bindings from Avoid binding of Xml Schema from Xml Schema example containing an element substitution group illustrates invalid element substitution handling.
6.7.4.1. Type Substitution of a Complex Type Definition
Complex Type Definition describes that when a complex type definition is mapped to Java value class that the type definition derivation hierarchy is preserved in the Java class hierarchy. This preservation makes it quite natural for Java to support the Xml Schema mechanism type substitution across all complex type definitions.
Performing an invalid type substitution is not detected as a fail-fast check when setting the JAXB property or checked as part of marshalling the element declaration. Invalid type substitution can be checked by optional validation that can be enabled as part of unmarshalling or marshalling process.
The following three code examples illustrate how type substitution is supported in JAXB for a complex type definition hierarchy.
<xs:schema targetNamespace="travel:acme" xmlns:a="travel:acme">
<!-- Define type definition derivation hierarchy -->
<xs:complexType name="TransportType">...</xs:complexType>
<xs:complexType name="PlaneType">
<xs:extension base="a:TransportType">...</xs:complexType>
<xs:complexType name="AutoType">
<xs:extension base="a:TransportType">...</xs:complexType>
<xs:complexType name="SUV">
<xs:extension base="a:AutoType">...</xs:complexType>
<xs:complexType name="itinerary">
<xs:sequence>
<!-- Type substitution possible for "transport". -->
<xs:element name="transport" type="TransportType"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
package travel.acme;
// Type derivation hierarchy from schema is preserved in Java binding.
public class TransportType {...}
public class PlaneType extends TransportType {...}
public class AutoType extends TransportType {...}
public class SUV extends AutoType {...}
public class ObjectFactory {
// Type Factories
TransportType createTransportType() {...}
AutoType createAutoType() {...}
PlaneType createPlaneType() {...}
TrainType createSUV() {...}
}
public class Itinerary {
// Simple property supports type substitution.
TransportType getTransport() {...}
void setTransport(TransportType value)
}
ObjectFactory of = ...;
Itinerary itinerary = of.createItinerary();
itinerary.setTransport(of.createTransportType); // Typical Use
// Type Substitution
// transport marshalled as <e:transport xsi:type="e:AutoType">
itinerary.setTransport(of.createAutoType());
// transport marshalled as <e:transport xsi:type="e:PlaneType">
itinerary.setTransport(of.createPlaneType());
6.7.4.2. Type Substitution of a Simple Type Definition
An XML element declaration having a simple type definition is bound most naturally to a JAXB property with a base type that is a primitive Java datatype. Unfortunately, this strongly typed binding conflicts with fully supporting type substitution of a simple type definition. Unlike the JAXB binding of complex type definitions, the simple type derivation hierarchy is not preserved when binding builtin XML Schema simple type definitions to corresponding Java datatypes as specified in Atomic Datatype. Since there is not a natural Java inheritance hierarchy to support simple type substitution, a JAXB property customization is required to enable optimal support of simple type substitution.
For example, the most natural binding of an
XML Schema built-in datatype xs:int
is to the Java primitive datatype,
int
. However, simple type substitution implies that an xs:short
or
a complex type definition that derives by extension from xs:int
can be
type substituted for an xs:int
within an XML document using the
xsi:type
attribute. The strongly typed JAXB property with Java type
int
would never allow for a Java value class for the complex type to
be assigned to a JAXB property of type int
.
By default, unmarshalling handles simple type substitution by assigning the relevant part of the type substituted content to the JAXB property. When the value of the xsi:type attribute resolves to:
-
a type that derives by restriction from the element’s schema type. The substituted value is always parsable into a legal value of the base type of the JAXB property being type substituted.
-
a complex type that derives by extension from element’s schema type. The JAXB binding of the substituted complex type definition must have one JAXB property annotated with an
@XmlValue
that is assignable to the type substituted JAXB property’s base type. Attribute(s) associated with the complex type definition can not be preserved by the default binding.
The rationale behind the default binding is
that substitution of a simple type definition occurs rarely. The default
JAXB binding is more convenient and precise for programmer to use. Its
one drawback is that it does not faithfully preserve xsi:type
occurring in an XML document.
To enable more comprehensive support of
simple type substituting of an XML element with a simple type
definition, the JAXB property customization specified in
Generalize/Specialize baseType with attribute @name enables
setting the property’s base type to the more
general type of java.lang.Object
. This binding allows for retention of
the XML document xsi:type
and attributes associated with complex type
definition substituted for an XML element with a simple type definition.
When an xsi:type
value refers to a type definition not registered with
JAXBContext
instance, the content is unmarshalled as the element’s
schema type.
To preserve an application-defined simple
type definition involved in simple type substitution, it must be mapped
to a JAXB mapped class as described in Bind to a JAXB mapped class.
This can be achieved for all simple type
definitions in a schema using the customization <jaxb:globalBinding
mapSimpleTypeDefs="true"/>
or it can be achieved per simple type
definition using <jaxb:class> customization. An invalid simple type
substitution can be detected by JAXP validation enabled at unmarshal
or marshal time
Below are examples of the type substitution of an XML element’s simple type definition for the default and customized binding.
<xsd:element name="Price">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<!-- element price subject to type substitution -->
<xsd:element name="price" type="xsd:int"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="AmountType">
<xsd:simpleContent> <!-- type substitutable for xs:int -->
<xsd:extension base="xsd:int">
<xsd:attribute name="currency" type="xsd:string"/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
<xsd:simpleType name="AppInt">
<xsd:restriction base="xsd:int"/>
</xsd:simpleType>
<product>
<name>hotdog</name>
<price>3</price>
</product>
<product>
<name>peanuts</name>
<price xsi:type="short">4</price>
</product>
<product>
<name>popcorn</name>
<price xsi:type="AppInt">5</price>
</product>
<product>
<name>sushi</name>
<price xsi:type="AmountType" currency="yen">500</price>
</product>
Default Handling of Simple Type Substitution
public class AmountType {
@XmlValue
int getValue() {...} void setValue(int value) {...}
String getCurrency() {...} void setCurrency(String value) {...}
}
@XmlRootElement(namespace="", name="product")
public class Product {
int getPrice() {...} void setPrice(int value) {...}
int getName() {...} void setName(String value) {...}
}
Unmarshalling XML document fragments from
XML documents with simple type substitution into Default JAXB binding of Schema fragment to illustrate simple type substitution JAXB binding of element product
results in the
xsi:type
and attributes associated with JAXB mapped class Price
being lost as part of the unmarshal process. This loss is illustrated by
comparing Product instances from unmarshalling XML docs from XML documents with simple type substitution with Product instances from unmarshalling XML docs from XML documents with simple type substitution.
document xsi:type | Product.name value |
Product.price value |
Product.price type |
marshal Product.price xsi:type |
---|---|---|---|---|
hotdog |
3 |
int |
||
xs:short |
peanuts |
4 |
int |
|
AppInt |
popcorn |
5 |
int |
|
AmountType |
sushi |
500 |
int |
Simple Type Substitution enabled by JAXB customizations.
The simple type definition AppInt
is mapped
to a JAXB class either by <jaxb:class>
customization or by
<jaxb:globalBindings mapSimpleTypeDef="true"/>
. The JAXB property
Product.Price
is mapped to a JAXB property with a general base type of
java.lang.Object
with following external JAXB schema customization:
<jaxb:bindings schemaLocation="CODE EXAMPLE"
node="//xsd:element[@name=’price’]">
<jaxb:property>
<jaxb:baseType name="java.lang.Object" />
</jaxb:property>
</jaxb:bindings>
specified in Generalize/Specialize baseType with attribute @name.
public class AmountType {
@XmlValue
int getValue() {...} void setValue(int value) {...}
String getCurrency() {...} void setCurrency(String value) {...}
}
public class AppInt {
@XmlValue
int getValue() {...} void setValue(int value) {...}
}
public class Product {
// enable simple type substitution with base type of Object
@XmlElement(type=java.lang.Integer.class)
Object getPrice() {...} void setPrice(Object value) {...}
int getName() {...} void setName(String value) {...}
}
Unmarshalling XML document fragments from
XML documents with simple type substitution
into Customized JAXB binding of Schema fragment to illustrate simple type substitution
JAXB binding of element product
preserves
the xsi:type
and attributes associated with JAXB mapped class
AmountType
is illustrated in Product instances from unmarshalling XML docs from XML documents with simple type substitution.
document xsi:type | Product.name value |
Product. price value |
Product. price Java type |
Marshal Product. price xsi:type |
---|---|---|---|---|
hotdog |
3 |
Integer |
||
xs:short |
peanuts |
4 |
Short |
xs:short |
AppInt |
popcorn |
5 |
AppInt |
AppInt |
AmountType |
sushi |
{value=500, |
AmountType |
AmountType |
6.7.5. Bind to a Simple Element property
Element substitution group is an Xml Schema mechanism that enables the substitution of one named element for another. This section uses terms and concepts described in Section 4.6 of [XSD Part 0] and normatively defined in Section 2.2.2.2 of [XSD Part 1].
The following constraints assist in defining the Java binding that enables element substitution group:
-
Element substitution is only possible for a reference to a global element.
-
Assuming the absence of the Xml Schema constraints on substitution, any global element can be made the head element of a substitution group.
-
-
All elements in a substitution group must derive from or have the same type definition as the head element.
To support element substitution, for
each global element reference to a head element of a substitution group
or to an abstract element, it is necessary to generate the Element
property bindings defined in Element Property.[21] This property enables the overriding
of the schema-specified element name bound to a JAXB property by setting
and getting the JAXB element representation,
jakarta.xml.bind.JAXBElement<T>
. The name property of the JAXBElement<T>
instance overrides the schema specified element declaration name.
To enable the passing of any element that could be part of the element
substitution group, it is necessary to accept any JAXBElement derivation
that extends Java binding of the head element’s type definition. Using
the upper bounded wildcard notation for a generic JAXBElement container,
JAXBElement<? extends T>
, the element property is able to get and set
any element that has an element value that is a subtype of T. Compile
time checking will not allow invalid JAXBElement derivations to be
passed to the Element property setter. When the element type is correct
but the element name is not part of the substitution group, this invalid
scenario can only be caught at runtime by validation or optional
fail-fast checking by the element property
setter.[22]
The schema-derived Element property getter
method is annotated, either explicitly or by default mapping
annotations, with the mapping annotation @XmlElementRef
, specified in
Section 8.10.3, “@XmlElementRef”. The @XmlElementRef
annotation
elements are derived in terms of the abstract model properties for the
referenced global element declaration summarized in
Element Declaration Schema Component as follows:
@XmlElementRef element | @XmlElementRef value |
---|---|
value |
jakarta.xml.bind.JAXBElement.class |
namespace |
referenced element declaration {target namespace} |
name |
referenced element declaration {name} |
Xml Schema example containing an element substitution group illustrates how to define an element substitution group and to reference the head element of the substitution group within an Xml Schema. Avoid binding of Xml Schema from Xml Schema example containing an element substitution group illustrates the Java bindings of the element substation enabled schema. Element substitution using Java bindings from Avoid binding of Xml Schema from Xml Schema example containing an element substitution group demonstrates element substitution using the JAXB API. Invalid element substitution using Java bindings from Avoid binding of Xml Schema from Xml Schema example containing an element substitution group illustrates invalid element substitution handling.
<xs:schema targetNamespace="travel:acme" xmlns:a="travel:acme">
<!-- See type definition derivation hierarchy defined in CODE EXAMPLE for
complexType definitions TransportType, PlaneType, AutoType and SUV.-->
<!-- Define element substitution group. a:transport is head element. -->
<xs:element name="transport" type="a:TransportType"/>
<xs:element name="plane" type="a:PlaneType" substitutionGroup="a:transport" />
<xs:element name="auto" type="a:AutoType" substitutionGroup="a:transport" />
<xs:complexType name="itinerary">
<xs:sequence>
<!-- Global element reference.
References head element of element substitution group. -->
<xs:element ref="a:transport"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
package travel.acme;
public class ObjectFactory {
// Type Factories
TransportType createTransportType();
AutoType createAutoType();
PlaneType createPlaneType();
TrainType createSUVType();
// Element Instance Factories
JAXBElement<AutoType> createAuto(AutoType value);
JAXBElement<PlaneType> createPlane(PlaneType value);
JAXBElement<TransportType> createTrain(TransportType value);
}
// See Java binding of type derivation hierarchy in CODE EXAMPLE 6-5
public class Itinerary {
// Element substitution supported by See [Element Property]
JAXBElement<? extends TransportType> getTransport();
void setTransport(JAXBElement<? extends TransportType> value);
}
ObjectFactory of = ...;
Itinerary itinerary = of.createItinerary();
itinerary.setTransport(of.createTransportType()); // Typical use.
// Element substitution:
// Substitute <e:auto> for schema specified <e:transport>.
itinerary.setTransport(of.createAuto(of.createAutoType()));
// Substitute <e:plane> for schema specified <e:transport>
itinerary.setTransport(of.createPlane(of.createPlaneType()));
// Combination of element and type substitution:
// Substitutes <e:auto xsi:type="e:SUV"> for <e:transport>
itinerary.setTransport(of.createAuto(of.createSUV()));
<!-- Add elements not part of element substitution group. -->
<xs:element name="apple" type="xsd:string"/>
<xs:complexType name="spaceShuttle">
<xs:extension base="a:TransportType">...</xs:complexType>
<xs:element name="spaceShuttle" type="a:spaceShuttleType">
ObjectFactory of = ...;
Itinerary itinerary = of.createItinerary();
// Invalid element substitution
// compile time error: method not found
// Element apple of type JAXBElement<String> does not match
// bounded wildcard JAXBElement<? extends TransportType>.
itinerary.setTransport(of.createApple("granny smith"));
// Invalid element substitution detected by validation.
// Element spaceShuttle not part of substitution group.
// Adding substitutionGroup="transport" to line 4 fixes this.
itinerary.setTranport(
of.createSpaceShuttle(of.createSpaceShuttleType()));
6.7.6. Bind to an Element Collection property
A repeating occurrence element declaration that is element substitutable binds solely to a JAXB Collection property of JAXBElement.
<!--deleted schema that remains same -->
<xs:complexType name="itinerary">
<xs:sequence>
<!-- Repeating occurance to substitutable global element reference. -->
<xs:element ref="a:transport" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
Java Binding:
public class Itinerary {
List<JAXBElement<? extends TransportType>> getTransport();
}
6.8. Attribute use
A ‘required’ or ‘optional’ attribute use is bound by default to a Java property as described in Properties. The characteristics of the Java property are derived in terms of the properties of the Attribute Use Schema Component and Attribute Declaration Schema Component as follows:
-
The name of the Java property is derived from the {attribute declaration} property’s {name} property using the XML Name to Java Identifier mapping algorithm described in The Name to Identifier Mapping Algorithm.
-
A base type for the Java property is derived from the
{attribute declaration}
property’s{type definition}
property as described in binding of Simple Type Definition in Simple Type Definition. If the base type is initially a primitive type and this JAXB property is optional , the [jaxb:globalBinding] customization@optionalProperty
controls the binding of an optional primitive property as described in Usage. -
An optional predicate for the Java property is constructed from the
{attribute declaration}
property’s{type definition}
property as described in the binding of simple type definition to a Java representation. -
An optional collection type for the Java property is derived from the
{attribute declaration}
property’s{type definition}
property as described in the binding of simple type definition to a Java representation. -
The default value for the Java property is the value from the attribute use’s {value constraint} property. If the optional {value constraint} is absent, the default value for the Java property is the Java default value for the base type.
-
The JAXB property is optional when the attribute use’s
{required}
property isfalse
.
This Java property is a member of the Java value class that represents the binding of the complex type definition containing the attribute use
The JAXB property getter for this attribute is annotated, either explicitly or via default mapping, with the mapping annotation @XmlAttribute, specified in @XmlAttribute. The @XmlAttribute element values are derived in terms of the properties of the Attribute Use Schema Component and Attribute Declaration Schema Component as follows:
@XmlAttribute element | @XmlAttribute value |
---|---|
name |
attribute declaration’s {name} |
namespace |
if attribute declaration’s {target namespace} absent,
set to “” |
required |
attribute use’s {required} |
Design Note
Since the target namespace is not being considered when mapping an attribute to a Java property, two distinct attributes that have the same {name} property but not the same {target namespace} will result in a Java property naming collision. As specified generically in Section D.2.1, “Collisions and conflicts”, the binding compiler detect this name collision between the two distinct properties and reports the error. The user can provide a customization that provides an alternative Java property name to resolve this situation. |
Example:
Given XML Schema fragment:
<xs:complexType name="USAddress">
<xs:attribute name="country" type="xs:string"/>
</xs:complexType>
Default derived Java code:
public class USAddress {
@XmlAttribute(name="country", targetNamespace="", required="false");
public String getCountry() {...}
public void setCountry(String value) {...}
}
6.8.1. Bind to a Java Constant property
Rather than binding to a read/write JAXB
property, an attribute use with a fixed
{value constraint} property
can be bound to a Java Constant property. This mapping is not performed
by default since fixed
is only a validation constraint. The user must
set the binding declaration attribute fixedAttributeToConstantProperty
on <jaxb:globalBinding>
element as specified in
Usage or on`<jaxb:property>` element
as specified in Usage to enable this
mapping.
Example:
Given XML Schema fragment:
<xs:annotation><xs:appinfo>
<jaxb:globalBindings fixedAttributeAsConstantProperty="true"/>
</xs:appinfo></xs:annotation>
<xs:complexType name="USAddress">
<xs:attribute name="country" type="xs:NMTOKEN" fixed="US"/>
</xs:complexType>
If the appropriate binding schema customization enables mapping a fixed XML value to Java constant property, the following Java code fragment is generated.
public class USAddress {
@XmlAttribute
public static final String COUNTRY="US";
...
}
The schema-derived constant for this fixed
attribute is annotated, either explicitly or via default mapping, with
the mapping annotation @XmlAttribute
. The elements of @XmlAttribute
are set as described in Annotate Attribute property getter method with @XmlAttribute annotation.
Note that if derivation by restriction constrains an existing attribute declaration to be fixed, this refinement must not be bound to a constant property. The initial binding of the attribute to a JAXB property remains the only binding of the attribute in the Java class hierarchy.
6.8.2. Binding an IDREF component to a Java property
An element or attribute with a type of
xs:IDREF
refers to the element in the instance document that has an
attribute with a type of xs:ID
or derived from type xs:ID
with the
same value as the xs:IDREF
value. Rather than expose the Java
programmer to this XML Schema concept, the default binding of an
xs:IDREF
component maps it to a Java property with a base type of
java.lang.Object
. The caller of the property setter method must be
sure that its parameter is identifiable. An object is considered
identifiable if one of its properties is derived from an element or
attribute that is or derives from type xs:ID
. The JAXB mapped class
must have one property annotated with an @XmlID
program annotation as it
is specified in Section 8. There is an expectation that all instances
provided as values for properties’ representing an xs:IDREF
should
have the Java property representing the xs:ID
of the instances set
before the content tree containing both the xs:ID
and xs:IDREF
is
marshalled. If a property representing an xs:IDREF
is set with an
object that does not have its xs:ID
set, the NotIdentifiableEvent
is
reported by marshalling.
-
The name of the Java property is derived from the {name} property of the attribute or element using the XML Name to Java Identifier mapping algorithm described in The Name to Identifier Mapping Algorithm.
-
A base type for the Java property is java.lang.Object.
-
There is no predicate for a property representing an
xs:IDREF
. -
An optional collection type
-
Default and fixed values can not be supported for an attribute with type
xs:IDREF
.
The schema-derived JAXB property representing xs:IDREF(s) is annotated, either explicitly or by default mapping annotations, with the mapping annotation @XmlIDREF, specified in Section 8.
Example:
Given XML Schema fragment:
<xs:complexType name="Book">
<xs:sequence>
<xs:element name="author" type="xs:IDREF"/>
<!-- ... -->
</xs:sequence>
</xs:complexType>
<xs:complexType name="AuthorBio">
<xs:sequence> <!-- ... --> </xs:sequence>
<xs:attribute name="name" type="xs:ID"/>
</xs:complexType>
Schema-derived Java value class:
public class Book {
@XmlIDREF
java.lang.Object getAuthor() {...}
/** Parameter referencedObj should have an attribute or
* child element with base type of xs:ID by validation
* or marshal time.
*/
void setAuthor(java.lang.Object referencedObj) {...}
}
public class AuthorBio {
@XmlID
String getName() {...}
void setName(String value) {...}
}
Demonstration of a Java content instance referencing another instance:
Book book = ...;
AuthorBio authorBio = ...;
book.setAuthor(authorBio);
authorBio.setName("<some author’s name>");
// The content instance root used to validate or marshal book must
// also include "authorBio" as a child element somewhere.
// A Java content instance is not included
Note that ID
and IDREF
mechanisms do not
incorporate type definitions that can be referenced. To generate
stronger typing for a JAXB property representing an IDREF, the schema
customization described in Generalize/Specialize baseType with attribute @name
can be used to specialize the binding. Specialize binding of an IDREF via customization
illustrates the generation of stronger typing for the above example.
6.9. Attribute Wildcard
Attribute wildcard is an extensibility feature in XML Schema. It enables an XML document author to introduce attribute(s) to an element that were not statically associated with the element’s complex type definition. Obviously, it is not possible to bind such an attribute to a strongly typed JAXB property as the previous section describes for attribute use schema component. The JAXB binding of a complex type definition that contains an attribute wildcard, directly or indirectly, provides dynamic access to the wildcard attributes via the following property:
// Return, by reference, a mapping of
attribute QName and String. +
Map<QName, String> getOtherAttributes();
The returned attribute map provides dynamic access to wildcard attributes associated with a complex type definition. The key to the map is the attribute’s QName and the key’s value is the String value of the attribute.
The schema-derived property getter method is
annotated, either explicitly or by default mapping annotations, with the
mapping annotation @XmlAnyAttribute
, specified in Section 8.
The following code examples show the JAXB binding for xs:anyAttribute and how to manipulate wildcard attributes using this binding.
<xs:schema targetNamespace="http://a.org">
<xs:complexType name="widget">
<xs:anyAttribute/>
<xs:attribute name="color" type="xs:string"/>
</xs:complexType>
</xs:schema>
package org.a;
import javax.xml.namespace.QName;
import java.util.Map;
public class Widget {
String getColor() {...}
void setColor(String value) {...}
@XmlAnyAttribute Map<QName, String> getOtherAttributes () {...}
}
import jakarta.xml.bind.DatatypeConverter;
Widget w = ...;
Map attrs = w.getOtherAttributes();
// access schema-defined global attribute associated with
// complexType defintion widget via attribute wildcard.
QName IS_OPEN = new QName("http://example.org", "isOpen");
boolean isOpen = DatatypeConverter.parseBoolean(attrs.get(IS_OPEN));
// set wildcard attribute value
attrs.put(IS_OPEN, DatatypeConverter.printBoolean(false));
// semantically the same results setting attribute use via
// dynamic or static setter for attribute use.
attrs.put(new QName("color"), "red");
// iterate over wildcard attributes
for (Map.Entry<QName,String> e: attrs.entrySet()) {
System.out.println("Attribute: " + e.getKey() +
" Value:" + e.getValue());
}
6.10. Redefine
Redefinition allows an existing XML Schema component to be “renamed” and its new definition takes the place of the old one. The binding of the redefined schema components, simple and complex type definitions and model and attribute group declarations, are described in the following subsections.
6.10.1. Bind Redefined Simple Type Definition
As introduced in Simple Type Definition, a schema component using a simple type definition typically binds to a JAXB property. The base type, collection type and predicate of the JAXB property are derived from the simple type definition. Thus, the redefine of a simple type definition results in the redefinition of the simple type definition being used to derive the base type, collection type and predicate of the JAXB property.
The one exception to this binding is that a simple type definition with enum facets is sometimes bound to an enum type. A redefined simple type definition that binds to an enum type, as described in Enum Type, is not bound to a Java representation, only the redefinition is bound to an enum type.
6.10.2. Bind Redefined Complex Type Definition
A redefinition of a type definition must use the original type definition as its base type definition. The redefined complex type definition is bound to a Java value class or interface name that prepends “_” to the class name. The redefinition complex type definition is bound to a class that extends the JAXB class that represents the redefined complex type definition.
File: v1.xsd:
<!-- Extracted from Section 4.2.2 of [XSD1] -->
<xs:complexType name="personName">
<xs:sequence>
<xs:element name="title" type="xs:string" minOccurs="0"/>
<xs:element name="forename" type="xs:string"
minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
File: v2.xsd:
<xs:redefine schemaLocation="v1.xsd">
<xs:complexType name="personName">
<xs:complexContent>
<xs:extension base="personName">
<xs:sequence>
<xs:element name="generation" minOccurs="0"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:redefine>
Java binding:
// binding of file v1.xsd complex type definition for personName
@XmlType(name="_PersonName")
public class _PersonName {
void setTitle(String value); String getTitle();
List<String> getForename();
}
// binding of v2.xsd redefinition for complex type personName
@XmlType(name="PersonName")
public class PersonName extends _PersonName {
void setGeneration(Object value); Object getGeneration();
}
6.10.3. Bind Redefined Group Definition
The attribute or model group redefinition is used instead of the initial group definition to construct the property set of the content model(s) that reference the redefined attribute or model group definition. The construction of a property set is described in Java value class.
Since there is no binding of an attribute or model group definition to a Java representation, no other special case handling is required for this binding.
6.11. Identity Constraint
An identity constraint does not represent any data, it represents a constraint that is enforced by validation. These constraints can be checked by optional validation that can be enabled at either unmarshal and/or marshal time.
6.12. Content Model - Particle, Model Group, Wildcard
This section describes the possible Java
bindings for the content model of a complex type definition schema
component with a {content type} property of mixed
or element-only
.
The possible element content(s) and the valid ordering between those
contents are constrained by the {particles} describing the complex type
definition’s content model. The Java binding of a content model is
realized by the derivation of one or more content-properties to
represent the element content constrained by the model group. Section
6.12.1 through 6.12.7 describes the element binding of a content
model.
6.12.1. Element binding style
The ideal Java binding would be to map each uniquely named element declaration occurring within a content model to a single JAXB property. The model group schema component constraint, element declarations consistent, specified in [XSD-Part 1] ensures that all element declarations/references having the same {target namespace} and {name} must have the same top-level type definition. This model allows the JAXB technology user to specify only the content and the JAXB implementation infers the valid ordering between the element content based on the {particles} constraints in the source schema.
However, there do exist numerous scenarios that this ideal binding is not possible for parts of the content model or potentially the entire content model. For these cases, default binding has a fallback position of representing the element content and the ordering between the content using a general content model. The scenarios where one must fallback to the general content model will be identified later in this subsection.
6.12.2. Bind each element declaration name to a JAXB property
This approach relies on the fact that a model group merely provide constraints on the ordering between children elements and the user merely wishes to provide the content. It is easiest to introduce this concept without allowing for repeating occurrences of model groups within a content model. Conceptually, this approach presents all element declarations within a content model as a set of element declaration {name}’s. Each one of the {name}’s is mapped to a content-property. Based on the element content that is set by the JAXB application via setting content-properties, the JAXB implementation can compute the order between the element content using the following methods.
Computing the ordering between element content within [children] of an element information item
-
Schema constrained fixed ordering or semantically insignificant ordering
The sequence in the schema represents an ordering between children elements that is completely fixed by the schema. Schema-constrained ordering is not exposed to the Java programmer when mapping each element in the sequence to a Java property. However, it is necessary for the marshal/unmarshal process to know the ordering. No new ordering constraints between children elements can be introduced by an XML document or Java application for this case. Additionally, the Java application does not need to know the ordering between children elements. When the compositor is
all
, the ordering between element content is not specified semantically and any ordering is okay. So this additional case can be handled the same way. -
Schema only constrains content and does not significantly constrain ordering
If the ordering between the children elements is significant and must be accessible to the Java application, then the ordering is naturally preserved in Java representation via a collection. Below are examples where schema provides very little help in constraining order based on content.
<xs:choice maxOccurs="unbounded"> ... </xs:choice> <xs:sequence maxOccurs="unbounded"> ... </xs:sequence>
6.12.3. General content property
A general content property is, as its name implies, the most general of all content properties. Such a property can be used with any content specification, no matter how complex. A general content property is represented as a List property as introduced in List Property. Unlike the prior approach where the JAXB implementation must infer ordering between the element content, this approach always requires the JAXB technology user to specify a valid ordering of element and text content. This approach has the benefit of providing the application with more control over setting and knowing the order between element content.
A general content property is capable of
representing both element information items and character data items
occurring within [children] of an element information item. Character
data is inserted into the list as java.lang.String values. Element data
is added to the list as instances of JAXB element. To support wildcard
content occurring as part of a general content property, xml data
content with no static Java binding is added and accessed from the list
as instances of org.w3c.org.dom.Node
.
The schema-derived Collection property getter method is annotated, either explicitly or by default mapping annotations, with the mapping annotations reflecting what content is within the Collection.
-
If the content model is mixed, the property is annotated as
@XmlMixed
. See Bind mixed content for details. -
Collection of Element types describes an optimized binding of a collection of element values, instead of a collection of JAXB elements annotated with
@XmlElementRefs(@XmlElementRef, …)
. -
If optimized binding can not be used, each element in the content model is represented by an
@XmlElementRef
, described in Bind to a Simple Element property. If there is more than one element annotations needed, they must occur as elements in the map annotation@XmlElementRefs
specified in Section 8.10.3, “@XmlElementRef”.
6.12.3.1. Collection of Element types
If the content model for a general content property meets all of the following constraints, the collection can be optimized to be a list of value classes instead of a list of JAXB elements.
-
If the content model is not mixed and does not contain a wildcard.
-
If none of the element declarations in the content model are abstract or the head of an element substitution group.
-
If none of the element declarations in the content model have a xml datatype that is or derives from xs:list or xs:IDREF.
-
For all element declarations in the content model, there does not exist two distinct element declarations whose types bind to the same Java datatype.
-
If not more than one element declaration in the content model is nillable.
Such a collection is annotated with @XmlElements
annotation,
specified in Section 8, that contains a
@XmlElement
annotation for each unique Java datatype within the
collection. The @XmlElement
annotation associates an element name with
each unique Java datatype in the collection
6.12.3.2. Examples
Example 1: Complex content model of Elements with primitive types
<xs:complexType name="Base">
<xs:choice maxOccurs="unbounded">
<xs:element name="A" type="xs:string"/>
<xs:element name="B" type="xs:string"/>
<xs:element name="C" type="xs:int"/>
</xs:choice>
</xs:complexType>
public class ObjectFactory \{
// Element instance factories.
JAXBElement<String> createBaseA(String value) {...}
JAXBElement<String> createBaseB(String value) {...}
JAXBElement<Integer> createBaseC(Integer value) {...}
// Type factories
Base createBase() {...}
}
public class Base {
/**
* A general content list that can contain
* element instances representing A, B and/or C.
*/
@XmlElementRefs({
@XmlElementRef(name="A", value=JAXBElement.class),
@XmlElementRef(name="B", value=JAXBElement.class),
@XmlElementRef(name="C", value=JAXBElement.class)})
List<JAXBElement> getAOrBOrC()\{...}
}
Example 2: Optimized Binding to a Collection of Element Types
XML Schema fragment:
<xs:complexType name="AType"/>
<xs:complexType name="BType"/>
<xs:complexType name="FooBar">
<xs:choice maxOccurs="unbounded">
<xs:element name="foo" type="AType"/>
<xs:element name="bar" type="BType"/>
</xs:choice>
</xs:complexType>
Default derived Java code:
public class AType {...}
public class BType {...}
class ObjectFactory {
// element instance factories only
JAXBElement<AType> createFooBarFoo(AType value);
JAXBElement<BType> createFooBarBar(BType value);
}
public class FooBar {
/** Collection of element types: AType and BType. */
@XmlElements({
@XmlElement(value=AType.class, name="Foo"),
@XmlElement(value=BType.class, name="Bar")})
List<Object> getFooOrBar() {...}
};
6.12.4. Bind mixed content
When a complex type definition’s {content type}
is “mixed,” its character and element information content is
bound to general content list as described in
General content property. Character
information data is inserted as instances of java.lang.String
into a
JAXB collection property.
The schema-derived Collection property getter
method is annotated, either explicitly or by default mapping
annotations, with the mapping annotation @XmlMixed
, specified in
Section 8.
Example:
Schema fragment loosely derived from mixed content example from [XSD Part 0].
<xs:element name="letterBody">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="productName" type="xs:string"/>
<!-- etc. -->
</xs:sequence>
</xs:complexType>
</xs:element>
Derived Java code:
import java.math.BigInteger;
class ObjectFactory {
// element instance factories only
JAXBElement<LetterBody> createLetterBody(LetterBody value);
JAXBElement<String> createLetterBodyName(String value);
JAXBElement<BigInteger> createLetterBodyQuantity(BigInteger value);
JAXBElement<String> createLetterBodyProductName(String value);
}
public class LetterBody implements JAXBElement<LetterBody> {
/** Mixed content can contain instances of Element classes
Name, Quantity and ProductName. Text data is represented as
java.util.String for text. */
@XmlMixed
@XmlElementRefs( {
@XmlElementRef(name="productName", type=JAXBElement.class),
@XmlElementRef(name="quantity", type=JAXBElement.class),
@XmlElementRef(name="name", type=JAXBElement.class)})
List getContent() {...}
}
The following instance document
<letterBody>
Dear Mr.<name>Robert Smith</name>
Your order of <quantity>1</quantity> <productName>Baby
Monitor</productName> shipped from our warehouse. ....
</letterBody>
could be constructed using JAXB API.
LetterBody lb = ObjectFactory.createLetterBody(null);
List gcl = lb.getContent();
gcl.add("Dear Mr.");
gcl.add(ObjectFactory.createLetterBodyName("Robert Smith"));
gcl.add("Your order of ");
gcl.add(ObjectFactory.
createLetterBodyQuantity(new BigInteger("1")));
gcl.add(ObjectFactory.createLetterBodyProductName("Baby Monitor"));
gcl.add("shipped from our warehouse");
Note that if any element instance is placed
into the general content list, gcl, that is not an instance of
LetterBody.Name
, LetterBody.Quantity
or LetterBody.ProductName
,
validation would detect the invalid content model. With the fail fast
customization enabled, element instances of the wrong type are detected
when being added to the general content list, gcl.
6.12.5. Bind wildcard schema component
A wildcard is mapped to a simple content-property with:
-
Content-property name set to the constant “
any
”. A binding schema customization could provide a more semantically meaningful content-property name. -
Content-property base type set to
java.lang.Object
by default. Wildcard content is represented as one of the following:-
JAXB element
Either an instance ofjakarta.xml.bind.JAXBElement<T>
or a JAXB class annotated with@XmlRootElement
.
Corresponds to a recognized global element tag name registered with the instancejakarta.xml.bind.JAXBContext
, meaning the schema(s) describing the element content is registered with the JAXBContext instance, see JAXBContext on how bindings are registered with aJAXBContext
instance., -
instance of
jakarta.xml.bind.JAXBElement
.
Corresponds to an unknown element name but a recognized type definition specified by @xsi:type on the element. JAXBElement declaredType is set tojava.lang.Object
since the unknown element declaration’s default type isxs:anyType
. -
element node instance of a supported xml infoset API.
Necessary to represent Xml data content that does not have a schema defined element or type definition. Such content is allowed by element xs:any with attribute @processContents="lax" or “skip”.
-
-
See content-property predicate for a wildcard.
-
If the
maxOccurs
is greater than one, the content property is mapped to a collection property. The default collection property is a List property of base type java.lang.Object. -
There is no default value.
Since the schema does not contain any information about the element content of a wildcard content, even the content-property, by default, can not infer an XML element tag for wildcard element content.
The schema-derived property getter method for
representing wildcard content is annotated, either explicitly or by
default mapping annotations, with the mapping annotation
@XmlAnyElement
, specified in Section 8. The @XmlAnyElement annotation
element values are derived in terms of the abstract model properties for
wildcard summarized in Wildcard Schema Component as follows:
@XmlAnyElement element | @XmlAnyElement element value |
---|---|
lax |
If wildcard schema component’s {process contents} is |
value |
|
6.12.6. Bind a repeating occurrence model group
A choice or sequence model group, containing
more than one member, with a repeating occurrence, maxOccurs
attribute
greater than one, is bound to a general content property in the
following manner:
-
Content-property name is derived in following ways:
-
If a named model group definition is being referenced, the value of its {name} property is mapped to a Java identifier for a method using the algorithm specified in The Name to Identifier Mapping Algorithm.
-
To derive a content property name for unnamed model group, see Deriving an identifier for a model group.
-
-
Content-property base type set to
java.lang.Object
. A binding schema customization could provide a more specialized java class. -
Content-property predicate validates the order between element instances in the list and whether the occurrence constraints for each element instance type is valid according to the schema.
-
Since the
maxOccurs
is always greater than one, the content property is mapped to a collection property. The default collection property is a List property. -
There is no default value.
The schema-derived collection property is annotated as specified in General content property and Collection of Element types.
Local structural Constraints
The list content property’s value must satisfy the content specification of the model group. The ordering and element contents must satisfy the constraints specified by the model group.
6.12.7. Content Model Default Binding
The following rules define element binding style for a complex type definition’s content model.
-
If {content type} is mixed, bind the entire content model to a general content property with the content-property name
"content"
. See Bind mixed content for more details. -
If (1) a particle has {max occurs} >1 and (2) its {term} is a model group and (3) all the particles in the model group have {terms} that bind to different Java datatypes, bind to a collection of element types. See complete list of constraints required to perform this optimized binding in Collection of Element types.
-
If (1) a particle has {max occurs} >1 and (2) its {term} is a model group, then that particle and its descendants are mapped to one general content property that represents them. See Bind a repeating occurrence model group for details.
-
Process all the remaining particles (1) whose {term} are wildcard particles and (2) that did not belong to a repeating occurrence model group bound in step 2. If there is only one wildcard, bind it as specified in Bind wildcard schema component. If there is more than one, then fallback to representing the entire content model as a single general content property. See General content property.
-
Process all particles (1) whose {term} are element declarations and (2) that do not belong to a repeating occurrence model group bound in step 2.
First, we say a particle has a label L if it refers to an element declaration whose {name} is L. Then, for all the possible pair of particles P and P’ in this set, if the following constraints are not met:
-
If P and P’ have the same label, then they must refer to the same element declaration.
-
If P and P’ refer to the same element reference, then its closest common ancestor particle may not have sequence as its {term}.
If either of the above constraints are violated, it is not possible to map each element declaration to a unique content property. Fallback to representing the entire content model as a single general content property.
Otherwise, create a content property for each label L as follows:
-
The content property name is derived from label name L.
-
The base type will be the Java type to which the referenced element declaration maps.
-
The content property predicate reflects the occurrence constraint.
-
The content property collection type defaults to
‘list’
if there exist a particle with label L that has {maxOccurs} > 1. -
For the default value, if all particles with label L has a {term} with the same {value constraint} default or fixed value, then this value. Otherwise none.
-
Below is an example demonstrating of not meeting the uniqueness constraints of 5(a) and 5(b) specified above.
<xs:sequence>
<xs:choice>
<xs:element ref="ns1:bar"/> (A)
<xs:element ref="ns2:bar"/> (B)
</xs:choice>
<xs:element ref="ns1:bar"/> (C)
</xs:sequence>
The pair (A,B) violates the first clause
because they both have the label “bar” but they refer to different
element declarations. The pair (A,C) violates the second clause because
their nearest common ancestor particle is the outermost <sequence>
.
This model group fragment is bound to a general content property.
6.12.7.1. Default binding of content model “derived by extension”
If a content-property naming collision occurs
between a content-property that exists in an base complex type
definition and a content-property introduced by a “derive by extension”
derived complex type definition, the content-properties from the
colliding property on are represented by a general content property with
the default property name rest
.
Example: derivation by extension content model with a content-property collision.
Given XML Schema fragment:
<xs:complexType name="Base">
<xs:sequence>
<xs:element name="A" type="xs:int"/>
<xs:element name="B" type="xs:int"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="Derived">
<xs:complexContent>
<xs:extension base="Base">
<xs:sequence>
<xs:element name="A" type="xs:int"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
Default binding derived Java code[23]:
public class Base {
int getA() {...} void setA(int) {...}
int getB() {...} void setB(int) {...}
}
public class Derived extends Base {
/**
* Instances of Derived.A must be placed in this general
* content propert that represents the rest of the content
* model. */
List getRest() {...}
}
class ObjectFactory {
// element instance factories only
JAXBElement<Integer> createDerivedA(Integer value) {...}
}
6.12.7.2. Bind single occurrence choice group to a choice content property
Setting the choiceContentProperty
attribute
of <jaxb:globalBindings>
as specified in
Usage enables this customized binding
option.
A non-repeating choice model group is bound to a simple property. The simple choice content property is derived from a choice model group as follows:
-
The choice content property name is either the referenced model group definition {name} or obtained using the algorithm specified in Deriving an identifier for a model group.
-
The choice content property
base type
is the first common supertype of all items within the choice model group, withjava.lang.Object
always being a common root for all Java objects.[24] -
The predicate
-
The collection type defaults to List if one or more items in the choice model group bind to List.
-
No default value.
A choice property consists of the following methods:
-
The
getChoiceID
method returns the set value. If the property has no set value then the valuenull
is returned. Note that a set value of a primitive Java type is returned as an instance of the corresponding Java wrapper class. -
The
setChoiceID
method has a single parameter that is the type of the choice content propertybase type
.
The globalBindings
and property
customization attribute, choiceContentProperty
, enables this
customized binding. The customization is specified in
<globalBindings>
Declaration.
Example:
XML Schema representation of a choice model group.
<xs:choice>
<xs:element name="foo" type="xs:int"/>
<xs:element name="bar" type="xs:string"/>
</xs:choice>
Derived choice content property method signatures:
void setFooOrBar(Object) {...}
Object getFooOrBar() {...}
6.13. Modifying Schema-Derived Code
There exist a number of use cases on why a developer would find it beneficial to modify schema-derived classes. Here are some of those use cases.
-
Add functionality to schema-derived classes.
Since schema-derived classes are derived from a data description language, the derived classes only represent data and have no object-level functionality. -
Add polymorphic methods to Java class hierarchy generated from XML Schema type definition derivation hierarchy.
-
Initialize a JAXB property or field representing an XML element with a default value. Regretfully, XML Schema element defaulting is insufficient to accomplish this. Note that XML Schema attribute defaulting is sufficient and does not require this approach.
The JAXB schema-derived class was designed to be easily understandable and modifiable by a developer. For many development environments, it is not sufficient to only run the schema compiler once due to modification of the schema-derived classes. Since schemas evolve over time, it is desirable to have the ability to regenerate schema-derived classes from an updated schema while preserving modification made by a developer. Given the complexities of supporting this capability, a JAXB implementation is not required to support regeneration from a schema into previously modified schema-derived classes. External tools, such as an IDE, could assist in supporting the sophisticated task of regeneration of a modified schema-derived class in the future. To enable tools to support regeneration, a JAXB implementation is required to have an option for generating an annotation that enables a portable means for distinguishing between developer code and generated code in a schema-derived class.The next section describes the portable format for distinguishing between generated and developer added/modified methods and/or fields in a schema-derived class.
6.13.1. Distinguish between generated and user added code
A schema compiler must have an option to
generate the Jakarta Annotation, @jakarta.annotation.Generated
annotation, specified in [CA], on every generated class, method and
field. If a developer does modify an @Generated
annotated method or
field, they must denote this modification by deleting the @Generated
annotation. If a developer adds a new method or field, it will not have
an @Generated
annotation on it. Based on these conventions, a JAXB
implementation in conjunction with an IDE or other external tool, would
be able to support regeneration of schema-derived code while preserving
developer additions/modifications to methods and fields in a
schema-derived class.
When schema compiler option to generate
@Generated
annotation is selected, the table describes the annotation
to be generated.
@Generated element | @Generated element value |
---|---|
value |
fully qualified class name of schema compiler |
date |
date of generation of schema-derived class. Value must follow the ISO 8601 standard. |
comment |
optional. Is implementation specific. |
6.14. Default Binding Rule Summary
Note that this summary is non-normative and all default binding rules specified previously in the chapter take precedence over this summary.
-
Bind the following to Java package:
-
XML Namespace URI
-
-
Bind the following XML Schema components to Java value class:
-
Named complex type
-
-
Bind to typesafe enum class:
-
A named simple type definition with a basetype that derives from
"xs:NCName"
and has enumeration facets.
-
-
Bind the following XML Schema components to an element instance factory that returns
jakarta.xml.bind.JAXBElement<T>
-
A global element declaration with a named type definition.
-
Local element declaration with a named type definition that can be inserted into a general content list.
-
-
Bind the following XML Schema components to a Java Element class
-
A global element declaration with anonymous type definition to a Java value class.
-
Local element declaration with anonymous type definition that can be inserted into a general content list.
-
-
Bind to Java property
-
Attribute use
-
Particle with a term that is an element reference or local element declaration.
Additionally, generate an element property for an element reference to the head element of a substitution group.
-
-
Bind to JAXB property:
getOtherAttributes(): java.util.Map<QName, String>
-
Attribute Wildcard occurring directly or indirectly via an attribute group reference in a complex type definition.
-
-
Bind model group and wildcard content with a repeating occurrence and complex type definitions with
mixed
{content type} to:-
A general content property - a List content-property that holds Java instances representing element information items and character data items. To support dynamic Xml content that validates against xs:any processContents=”lax” or “skip”, allow instances of org.w3c.dom.Node into the list.
-
XML Schema | Java Representation |
---|---|
Schema targetNamespace |
Package |
Global Element Declaration with named type definition |
ObjectFactory.elementInstanceFactory method returning JAXBElement<T> Value must follow the ISO 8601 standard. |
Global Complex Type Definition (Named) |
value class/class + ObjectFactory.typeInstanceFactory method |
Global Simple Type Definition
|
enum type |
SimpleType facets |
ConstraintPredicate |
Attribute Uses Local Element Declaration |
Property |
facet @maxOccurs > 1 xsd:list |
PropertyStyle List |
@fixedPropertyStyle |
Constant |
Global Element Declaration with anonymous type definition |
value class for anonymous type + ObjectFactory.typeInstanceFactory + ObjectFactory.elementInstanceFactory method |
Element reference to SubstitutionGroup Head maxOccurs = “1” |
Simple + Element property |
Element reference to SubstitutionGroup Head maxOccurs > “1” |
List<JAXBElement<T>> |
7. Customizing XML Schema to Java Representation Binding
The default binding of source schema components to derived Java representation by a binding compiler sometimes may not meet the requirements of a JAXB application. In such cases, the default binding can be customized using a binding declaration. Binding declarations are specified by a binding language, the syntax and semantics of which are defined in this chapter.
All JAXB implementations are required to provide customization support specified here unless explicitly stated as optional.
7.1. Binding Language
The binding language is an XML based language which defines constructs referred to as binding declarations. A binding declaration can be used to customize the default binding between an XML schema component and its Java representation.
The schema for binding declarations is defined in the namespace
https://jakarta.ee/xml/ns/jaxb
. This specification uses the
namespace prefix "jaxb"
to refer to the namespace of binding
declarations. For example,
<jaxb: binding declaration>
A binding compiler interprets the binding declaration relative to the source schema and a set of default bindings for that schema. Therefore a source schema need not contain a binding declarations for every schema component. This makes the job of a JAXB application developer easier.
There are two ways to associate a binding declaration with a schema element:
-
as part of the source schema (inline annotated schema)
-
external to the source schema in an external binding declaration.
The syntax and semantics of the binding declaration is the same regardless of which of the above two methods is used for customization.
A binding declaration itself does not identify the schema component to which it applies. A schema component can be identified in several ways:
-
explicitly - e.g. QName, XPath expressions etc.
-
implicitly - based on the context in which the declaration occurs.
It is this separation which allows the binding declaration syntax to be shared between inline annotated schema and the external binding.
7.1.1. Extending the Binding Language
In recognition that there will exist a need for additional binding declarations than those currently specified in this specification, a formal mechanism is introduced so all JAXB processors are able to identify extension binding declarations . An extension binding declaration is not specified in the jaxb: namespace, is implementation specific and its use will impact portability. Therefore, binding customization that must be portable between JAXB implementations should not rely on particular customization extensions being available.
The namespaces containing extension binding
declarations are specified to a JAXB processor by the occurrence of the
global attribute <jaxb:extensionBindingPrefixes>
within an instance of
<xs:schema>
element. The value of this attribute is a
whitespace-separated list of namespace prefixes. The namespace bound to
each of the prefixes is designated as a customization declaration
namespace. Prefixes are resolved on the <xs:schema>
element that
carries this attribute. It is an error if the prefix fails to resolve.
This feature is quite similar to the extension-element-prefixes
attribute in [XSLT 1.0] http://www.w3.org/TR/xslt10/#extension
,
introduces extension namespaces for extension instructions and functions
for XSLT 1.0.
This specification does not define any mechanism for creating or processing extension binding declarations and does not require that implementations support any such mechanism. Such mechanisms, if they exist, are implementation-defined.
7.1.2. Inline Annotated Schema
This method of customization utilizes on the
<appinfo>
element specified by the XML Schema [XSD PART 1]. A binding
declaration is embedded within the <appinfo>
element as illustrated
below.
<xs:annotation>
<xs:appinfo>
<binding declaration>
</xs:appinfo>
</xs:annotation>
The inline annotation where the binding declaration is used identifies the schema component.
7.1.3. External Binding Declaration
The external binding declaration format
enables customized binding without requiring modification of the source
schema. Unlike inline annotation, the remote schema component to which
the binding declaration applies must be identified explicitly. The
<jaxb:bindings>
element enables the specification of a remote schema
context to associate its binding declaration(s) with. Minimally, an
external binding declaration follows the following format.
<jaxb:bindings [schemaLocation = "xs:anyURI"]>
<jaxb:bindings [node = "xs:string"]>
<binding declaration>
<jaxb:bindings>
</jaxb:bindings>
The schemaLocation attribute is optional for
specifying <jaxb:globalBindings>
, and the node attribute is optional
for specifying <jaxb:schemaBindings>
. The attributes schemaLocation
and node are used to construct a reference to a node in a remote
schema. The binding declaration is applied to this node by the binding
compiler as if the binding declaration was embedded in the node’s
<xs:appinfo>
element. The attribute values are interpreted as follows:
-
schemaLocation - It is a URI reference to a remote schema.
-
node - It is an XPath 1.0 expression that identifies the schema node within schemaLocation to associate binding declarations with.
An example external binding declaration can be found in Example.
7.1.3.1. Restrictions
-
The external binding element
<jaxb:bindings>
is only recognized for processing by a JAXB processor when its parent is an<xs:appinfo>
element, it is an ancestor of another<jaxb:bindings>
element, or when it is root element of a document. An XML document that has a<jaxb:bindings>
element as its root is referred to as an external binding declaration file. -
The top-most
<jaxb:binding>
element within an<xs:appinfo>
element or the root element of an external binding file must have its schemaLocation attribute set.
7.1.4. Version Attribute
The normative binding schema specifies a
global version
attribute. It is used to identify the version of the
binding declarations. For example, a future version of this
specification may use the version attribute to specify backward
compatibility. To indicate this version of the specification, the
version should
be "3.0"
.
If any other version is specified, it must result in an invalid
customization as specified in Invalid Customizations.
The version
attribute must be specified in
one of the following ways:
-
If customizations are specified in inline annotations, the
version
attribute must be specified in<xs:schema>
element of the source schema. For example,<xs:schema jaxb:version="3.0">
-
If customizations are specified in an external binding file, then the
jaxb:version
attribute must be specified in the root element<jaxb:bindings>
in the external binding file. Alternately, a localversion
attribute may be used. Thus the version can be specified either as<jaxb:bindings version="3.0" ... />
or
<jaxb:bindings jaxb:version="3.0" ... />
Specification of both
version
and<jaxb:version>
must result in an invalid customization as specified in Invalid Customizations.
7.1.5. Invalid Customizations
A non conforming binding declaration is a
binding declaration in the jaxb
namespace but does not conform to this
specification. A non conforming binding declaration results in a
customization error. The binding compiler must report the customization
error. The exact error is not specified here. For additional
requirements see Compatibility.
The rest of this chapter assumes that non conforming binding declarations are processed as indicated above and their semantics are not explicitly specified in the descriptions of individual binding declarations.
7.2. Notation
The source and binding-schema fragments shown in this chapter are meant to be illustrative rather than normative. The normative syntax for the binding language is specified in Normative Binding Schema Syntax in addition to the other normative text within this chapter. All examples are non-normative.
-
Metavariables are in italics.
-
Optional attributes are enclosed in
[ square="bracket" ]
. -
Optional elements are enclosed in
[ <elementA> … </elementA> ]
. -
Other symbols: ‘
,
’ denotes a sequence, ‘|
’ denotes a choice, ‘+
’ denotes one or more, ‘*
’ denotes zero or more. -
The prefix
xs:
is used to refer to schema components in W3C XML Schema namespace. -
In examples, the binding declarations as well as the customized code are shown in bold like this: <appinfo> <annotation> or getAddress().
7.3. Naming Conventions
The naming convention for XML names in the binding language schema are:
-
The first letter of the first word in a multi word name is in lower case.
-
The first letter of every word except the first one is in upper case.
For example, the XML name for the Java property basetype is baseType.
7.4. Customization Overview
A binding declaration customizes the default binding of a schema element to a Java representation. The binding declaration defines one or more customization values each of which customizes a part of Java representation.
7.4.1. Scope
When a customization value is defined in a binding declaration, it is associated with a scope. A scope of a customization value is the set of schema elements to which it applies. If a customization value applies to a schema element, then the schema element is said to be covered by the scope of the customization value. The scopes are:
-
global scope: A customization value defined in
<globalBindings>
has global scope. A global scope covers all the schema elements in the source schema and (recursively) any schemas that are included or imported by the source schema. -
schema scope: A customization value defined in
<schemaBindings>
has schema scope. A schema scope covers all the schema elements in the target namespace of a schema. -
definition scope: A customization value in binding declarations of a type definition or global declaration has definition scope. A definition scope covers all schema elements that reference the type definition or the global declaration. This is more precisely specified in the context of binding declarations later on in this chapter.
-
component scope: A customization value in a binding declaration has component scope if the customization value applies only to the schema element that was annotated with the binding declaration.
The different scopes form a taxonomy. The taxonomy defines both the inheritance and overriding semantics of customization values. A customization value defined in one scope is inherited for use in a binding declaration covered by another scope as shown by the following inheritance hierarchy:
-
a schema element in schema scope inherits a customization value defined in global scope.
-
a schema element in definition scope inherits a customization value defined in schema or global scope.
-
a schema element in component scope inherits a customization value defined in definition, schema or global scope.
Likewise, a customization value defined in one scope can override a customization value inherited from another scope as shown below:
-
value in schema scope overrides a value inherited from global scope.
-
value in definition scope overrides a value inherited from schema scope or global scope.
-
value in component scope overrides a value inherited from definition, schema or global scope.
7.4.2. XML Schema Parsing
Chapter 5 specified the bindings using the abstract schema model. Customization, on the other hand, is specified in terms of XML syntax not abstract schema model. The XML Schema specification [XSD PART 1] specifies the parsing of schema elements into abstract schema components. This parsing is assumed for parsing of annotation elements specified here. In some cases, [XSD PART 1] is ambiguous with respect to the specification of annotation elements. Annotation Restrictions outlines how these are addressed.
Design Note
The reason for specifying using the XML syntax instead of abstract schema model is as follows. For most part, there is a one-to-one mapping between schema elements and the abstract schema components to which they are bound. However, there are certain exceptions: local attributes and particles. A local attribute is mapped to two schema components: {attribute declaration} and {attribute use}. But the XML parsing process associates the annotation with the {attribute declaration} not the {attribute use}. This is tricky and not obvious. Hence for ease of understanding, a choice was made to specify customization at the surface syntax level instead. |
7.5. <globalBindings>
Declaration
The customization values in "<globalBindings>"
binding declaration have global scope. This binding
declaration is therefore useful for customizing at a global level.
7.5.1. Usage
<globalBindings
[ collectionType = "collectionType" ]
[ fixedAttributeAsConstantProperty = "true" | "false" | "1" | "0" ]
[ generateIsSetMethod = "true" | "false" | "1" | "0" ]
[ enableFailFastCheck = "true" | "false" | "1" | "0" ]
[ choiceContentProperty = "true" | "false" | "1" | "0" ]
[ underscoreBinding = "asWordSeparator" | "asCharInWord" ]
[ typesafeEnumBase = "typesafeEnumBase" ]
[ typesafeEnumMemberName = "skipGeneration" |
"generateName" | "generateError" ]
[ typesafeEnumMaxMembers = “xxxx”]
[ enableJavaNamingConventions = "true" | "false" | "1" | "0" ]
[ generateElementClass = "false" | "true" | "0" | "1" ]
[ generateElementProperty = "false" | "true" | "0" | "1" ]
[ generateValueClass = "true" | "true" | "0" | "1" ]
[ optionalProperty = "wrapper" | "primitive" | "isSet" ]
[ mapSimpleTypeDef = "true" | "false" | "1" | "0" ]
[ localScoping = "nested" | "toplevel" ] >
[ <javaType> ... </javaType> ]*
[ <serializable uid=”xxxx”/> ]*
</globalBindings>
The following customization values are defined in global scope:
-
collectionType
if specified, must be either"indexed"
or any fully qualified class name that implementsjava.util.List
. The default value is to any fully qualified class name that implementsjava.util.List
. -
fixedAttributeAsConstantProperty
if specified , defines the customization valuefixedAttributeAsConstantProperty
. The value must be one of"true"
,"false"
,"1"
or"0"
. The default value is"false"
. -
generateIsSetMethod
if specified, defines the customization value ofgenerateIsSetMethod
. The value must be one of"true"
,"false"
,"1"
or"0"
. The default value is"false"
. Consider customizing using the newly introduced optionalProperty before using this JAXB customization. -
enableFailFastCheck
if specified, defines the customization valueenableFailFastCheck`. The value must be one of `"true"
,"false"
,"1"
or"0"
. If enableFailFastCheck is"true"
or"1"
and the JAXB implementation supports this optional checking, type constraint checking when setting a property is performed as described in Properties. The default value is"false"
. -
choiceContentProperty
if specified, defines the customization valuechoiceContentProperty
. The value must be one of"true"
,"false"
,"1"
or"0"
. The default value is"false"
. -
underscoreBinding
if specified, defines the customization valueunderscoreBinding
. The value must be one of"asWordSeparator"
or"asCharInWord"
. The default value is"asWordSeparator"
. -
enableJavaNamingConventions
if specified, defines the customization valueenableJavaNamingConventions
. The value must be one of"true"
,"false"
,"1"
or"0"
. The default value is"true"
. -
typesafeEnumBase
if specified, defines the customization valuetypesafeEnumBase
. The value must be a list of QNames, each of which must resolve to a simple type definition. Only simple type definitions with an enumeration facet and a restriction base type listed intypesafeEnumBase
or derived from a type listed intypesafeEnumBase
is bound to atypesafeEnumClass
by default as specified in Enum Type. The default value oftypesafeEnumBase
is"xs:string"
.The
typesafeEnumBase
cannot contain the following simple types and therefore a JAXB implementation is not required to support the binding of the these types to typesafe enumeration class:"xs:QName"
,"xs:NOTATIION"
,"xs:base64Binary"
,"xs:hexBinary"
,"xs:date"
,"xs:time"
,"xs:dateTime"
,"xs:duration"
,"xs:gDay"
,"xs:gMonth"
,"xs:gYear"
,"xs:gMonthDay"
,"xs:gYearMonth"
,"xs:IDREF"
,"xs:ID"
. If any of them are specified, it must result in an invalid customization as specified in Invalid Customizations. JAXB implementation must be capable of binding any other simple type listed intypesafeEnumBase
to a typesafe enumeration class. -
typesafeEnumMemberName
if specified, defines the customization valuetypesafeEnumMemberName
. The value must be one ofskipGeneration
,generateError
orgenerateName
. The default value isskipGeneration
. See @typesafeEnumMemberName for details. -
typesafeEnumMaxMembers
if specified, defines the maximum number of enum facets that a simple type definition can have and be consider to binding to an enum type by default. The attributes type isxs:int
and its default value is256
. -
generateElementClass
if specified as true, a schema-derived Element class, as specified in Java Element Class, is generated for each element declaration that has an element factory method generated for it. Its default value is"false"
. -
generateElementProperty
if specified as true, controls the generation of JAXBElement property. The value must be one of"true"
,"false"
,"1"
or"0"
. The default is absence of the value. -
generateValueClass
if specified as true, a schema-derived Java value class is generated for each complex type definiton.Value class is specified in Value Class. If generateValueClass is specified as false, a schema-derived interface and implementation class is generated for each complex type definition as specified in Java Content Interface. The attribute’s default value is true. See examples of this binding in generateElementClass and generateValueClass. -
zero or more
javaType
binding declarations. Each binding declaration must be specified as described in<javaType>
Declaration. -
zero or one serializable binding declaration.
-
optionalProperty
controls how a JAXB property with a primitive base type that represents an optional non-nillable element/attribute is bound. If the attribute has the value "wrapper", then the base type of the JAXB property is the wrapper class for the primitive type. A user can indicate that this optional property is not set by calling the setter with “null” value. If the attribute’s value is "primitive", it binds as it did in JAXB 1.0. If the attribute’s value is “isSet”, it binds the optional property using the primitive base type and also the isSet/unset methods are generated for the optional property. The attribute’s default value is “wrapper”. -
mapSimpleTypeDef
controls whether a JAXB mapped class should be generated for each simple type definition as specified in Bind to a JAXB mapped class. This attribute’s default value is"false"
. This customization eases preserving simple type substituting precisely as described in Type Substitution of a Simple Type Definition. -
localScoping
attribute can have the value of either nested or toplevel . This attribute describes the JAXB binding of nested XML schema component to either a nested schema-derived JAXB class or a toplevel schema-derived JAXB class. To avoid naming collisions between nested components, the default value for this attribute is nested. A developer can customize localScoping to toplevel when schema components nest too deeply or an application would prefer to not work with nested classes.
The semantics of the above customization values, if not specified above, are specified when they are actually used in the binding declarations.
For inline annotation, a <globalBindings>
is valid only in the annotation element of the <schema>
element. There
must only be a single instance of a <globalBindings>
declaration in
the annotation element of the <schema>
element.
7.5.2. Customized Name Mapping
A customization value can be used to specify a name for a Java object (e.g. class name, package name etc.). In this case, a customization value is referred to as a customization name.
A customization name is always a legal Java identifier (this is formally specified in each binding declaration where the name is specified). Since customization deals with customization of a Java representation to which an XML schema element is bound, requiring a customization name to be a legal Java identifier rather than an XML name is considered more meaningful.
A customization name may or may not conform to the recommended Java language naming conventions. [JLS - Java Language Specification, Second Edition, Section 6.8, "Naming Conventions"]. The customization value enableJavaNamingConventions determines if a customization name is mapped to a Java identifier that follows Java language naming conventions or not.
If enableJavaNamingConventions is defined and
the value is "true"
or "1"
, then the customization name (except for
constant name) specified in the section from where this section is
referenced must be mapped to Java identifier which follows the Java
language naming conventions as specified in
Conforming Java Identifier Algorithm;
otherwise the customized name must be used as is.
7.5.3. Underscore Handling
The [jaxb:globalBindings] attribute customization underscoreBinding allows for the preservation of underscore(s) occurring in an XML name when deriving a a Java identifier from it.
The default value for @underscoreBinding is
"asWordSeparator"
and categorizes underscore (‘_’) as a punctuation
mark in the XML name to Java identifier algorithm specified in Appendix
The Name to Identifier Mapping Algorithm.
The resulting algorithm transforms one or more consecutive
underscores in an XML name to camel case separated words in the derived
Java class and method names. Examples of this mapping are in
XML Names and derived Java Class, Method, and Constant Names.
When @underscoreBinding is
"asCharInWord"
, underscore (‘_’) is considered a special letter within
a word. The result is that all underscore characters from the original
XML name are preserved in the derived Java identifier. Example of this
mapping are in XML Names and derived Java Class, Method, and Constant Names when <jaxb:globalBindings underscoreHandling=”asCharInWord”>.
7.5.4. generateElementClass and generateValueClass
The following code examples illustrate default binding to value class and customization to bind to interface/implementation classes.
Example: Default Binding to a value class.
Schema fragment:
<xs:complexType name="USAddress">
<xs:attribute name="City" type="xs:string"/>
</xs:complexType>
Default Value Class:
public class USAddress {
public USAddress() {...}
public String getCity() {...}
public void setCity(String value) {...}
...
}
Customization <jaxb:globalBinding generateValueClass="false">
generates following interface instead of
default value class:
Example: Customized binding to an interface.
public interface USAddress {
String getCity();
void setCity(String value);
}
Example: Generation of an Element Class.
Schema fragment:
<xs:element name="Address" type="USAddress"/>
// Default Java binding of global element to element instance factory
public ObjectFactory {
JAXBElement<USAddress> createAddress(USAddress value);
}
<jaxb:globalBinding generateElementClass="true"/>
results in generation
of following Element class:
public class Address extends JAXBElement<USAddress> {
}
7.5.5. @typesafeEnumMemberName
If there is a collision among the generated
constant fields name or if it is not possible to generate a legal Java
identifier for one or more of the generated constant field names, then
the binding is determined based on the value of @
typesafeEnumMemberName
of element [jaxb:globalBindings].
-
skipGeneration
An enum type is not generated. This is the default behavior iftypesafeEnumMemberName
has not been specified. A binding compiler may report a warning on why the simple type definition was not bound to an enum type. -
generateName
The constant fields name is