Specification: Jakarta XML Binding Version: 3.0 Status: Rev1 Release: March 23, 2021
Copyright (c) 2019, 2021 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. JAXB 1.0 made it possible to do this at any time, without the user having to first marshal the tree into XML. However it is a non goal in Jakarta XML Binding specification, which leverages the JAXP validation API. -
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.
-
deprecation of on-demand validation.
-
unmarshal/marshal time validation deferring to JAXP 1.3 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
[4] 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[5]
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[5] 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; }[6]
@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 deprecated in Jakarta XML Binding. See On-demand Validation for the JAXB 1.0 description of this functionality. -
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 1.3 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 {
static final string JAXB_ENCODING;
static final string JAXB_FORMATTED_OUTPUT;
static final string JAXB_SCHEMA_LOCATION;
static final string JAXB_NO_NAMESPACE_SCHEMA_LOCATION;
static final 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 1.3
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 1.3 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):
-
Context path or classes’ packages explicitly passed in to the newInstance method are searched for the jaxb.properties file.
If such a resource is discovered, it is loaded as a property file, and the value of thejakarta.xml.bind.JAXBContextFactory
key will be assumed to be the provider factory class. If no value found,jakarta.xml.bind.context.factory
is used as a key for backwards compatibility reasons.
This configuration method is deprecated. -
If the system property
jakarta.xml.bind.JAXBContextFactory
exists, then its value is assumed to be the provider factory class. If no such property exists, propertiesjakarta.xml.bind.context.factory
andjakarta.xml.bind.JAXBContext
are checked too (in this order), for backwards compatibility reasons. -
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. -
Look for resource
/META-INF/services/jakarta.xml.bind.JAXBContext
. If such a resource exists, its content is assumed to be the provider factory class.
This configuration method is deprecated. -
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.[7] -
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[8] 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[9]. 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[10], 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[7] 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[7], 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.[11]
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.[12] 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 [16] |
xsd:dateTime |
javax.xml.datatype.XMLGregorianCalendar [16] |
xsd:base64Binary |
byte[] |
xsd:hexBinary |
byte[] |
xsd:unsignedInt |
long |
xsd:unsignedShort |
int |
xsd:unsignedByte |
short |
xsd:time |
javax.xml.datatype.XMLGregorianCalendar [16] |
xsd:date |
javax.xml.datatype.XMLGregorianCalendar [16] |
xsd:g* |
javax.xml.datatype.XMLGregorianCalendar [16] |
xsd:anySimpleType |
java.lang.Object |
xsd:anySimpleType |
java.lang.String |
xsd:duration |
javax.xml.datatype.Duration [16] |
xsd:NOTATION |
javax.xml.namespace.QName [16] |
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
[18] 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[19] 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[20], 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.[21]
-
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.[22] 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.[23]
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[24]:
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.[25] -
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"VALUE_<N>"
where<N>
is 1 for the first enumeration value and increments by 1 to represent each value within the XML enumeration. -
generateError
An error must be reported.
7.5.6. <serializable> Declaration
When the serializable customization is
specified, all schema-derived classes implement java.io.Serializable
.
Each class is generated with a serialVersionUID
field set to the value
specified by @uid.
private static final long serialVersionUID = <value of @uid>;
The JAXB user is required to identify when
schema-derived classes do not follow
Java
serialization class evolution rules and change the generated
serialVersionUID
field by changing the [serializable] element’s
attribute @uid value.
7.5.7. @generateElementProperty
Some schemas use both minOccurs="0" on element as well as nillable="true", causing the generation of JAXBElement. This customization lets you control this behavior. This attribute may take two values:
-
true:
Always generate properties to use JAXBElement, unless overriden by<jaxb:property generateElementProperty="false"/>
on individual property. -
false:
When generating properties from<element nillable=”true” minOccurs=”0”/>
, generate a property not to use JAXBElement, as if the element declaration were just<element nillable=”true” />
, unless overriden by<jaxb:property generateElementProperty="true"/>
on individual property. It is an error to specify this customization, when the property is required to be JAXBElement (such as when a property contains multiple elements with different names but of the same type.)
7.6. <schemaBindings>
Declaration
The customization values in
<schemaBindings>
binding declaration have schema scope. This binding
declaration is therefore useful for customizing at a schema level.
7.6.1. Usage
<schemaBindings [ map="boolean" ] >
[ <package> package </package> ]
[ <nameXmlTransform> ... </nameXmlTransform>]*
</schemaBindings>
<package [ name = "packageName" ]
[ <javadoc> ... </javadoc> ]
</package>
<nameXmlTransform>
[ <typeName [ suffix="suffix" ]
[ prefix="prefix" ] /> ]
[ <elementName [ suffix="suffix" ]
[ prefix="prefix" ] /> ]
[ <modelGroupName [ suffix="suffix" ]
[ prefix="prefix" ] /> ]
[ <anonymousTypeName [ suffix="suffix" ]
[ prefix="prefix" ] /> ]
</nameXmlTransform>
For readability, the <nameXmlTransform>
and
<package>
elements are shown separately. However, they are local
elements within the <schemaBindings>
element.
The following customizations are defined in the schema scope:
-
map if specified, prevents the classes from being generated from this schema. When the value is
"0"
or"false"
, then no class/interface/enum will be generated from this package. map defaults to"true"
.
The semantics of the customization value, if not specified above, are specified when they are actually used in the binding declarations.
For inline annotation, a <schemaBindings>
is valid only in the annotation element of the <schema>
element. There
must only be a single instance of a <schemaBindings>
declaration in
the annotation element of the <schema>
element.
If one source schema includes (via the
include mechanism specified by XSD PART 1) a second source schema, then
the <schemaBindings>
declaration must be declared in the first
including source schema. It should be noted that there is no such
restriction on <schemaBindings>
declarations when one source schema
imports another schema since the scope of <schemaBindings>
binding
declaration is schema scope.
7.6.1.1. package
Usage
-
name
if specified, defines the customization valuepackageName
.packageName
must be a valid Java package name. -
<javadoc>
if specified, customizes the package level Javadoc.<javadoc>
must be specified as described in<javadoc>
Declaration. The Javadoc must be generated as specified in Javadoc Customization. The Javadoc section customized is thepackage section
.
Design Note
The word “package” has been prefixed to |
The semantics of the packageName
is
specified in the context where it is used. If neither packageName
nor
the <javadoc>
element is specified, then the binding declaration has
no effect.
Example: Customizing Package Name
<jaxb:schemaBindings>
<jaxb:package name = "org.example.po" />
</jaxb:schemaBindings>
specifies "org.example.po"
as the package
to be associated with the schema.
7.6.1.2. nameXmlTransform
The use case for this declaration is the UDDI Version 2.0 schema. The UDDI Version 2.0 schema contains many declarations of the following nature:
<xs:element name="bindingTemplate" type="uddi:bindingTemplate"/>
The above declaration results in a name
collision since both the element and type names are the same - although
in different XML Schema symbol spaces. Normally, collisions are supposed
to be resolved using customization. However, since there are many
collisions for the UDDI V2.0 schema, this is not a convenient solution.
Hence the binding declaration nameXmlTransform
is being provided to
automate name collision resolution.
The nameXmlTransform
allows a suffix
and
a prefix
to be specified on a per symbol space basis. The following
symbol spaces are supported:
-
<typeName>
for the symbol space “type definitions” -
<elementName>
for the symbol space “element definitions” -
<modelGroupName>
for the symbol space “model group definitions.” -
<anonymousTypeName>
for customizing Java value class to which an anonymous type is bound.[26]
If suffix
is specified, it must be appended
to all the default XML names in the symbol space. The prefix
if
specified, must be prepended to the default XML name. Furthermore, this
XML name transformation must be done after the XML name to Java
Identifier algorithm is applied to map the XML name to a Java
identifier. The XML name transformation must not be performed on
customization names.
By using a different prefix
and/or suffix
for each symbol space, identical names in different symbol spaces can be
transformed into non-colliding XML names.
anonymousTypeName
The <anonymousTypeName>
declaration can be
used to customize the suffix and prefix for the Java value class. If
prefix
is specified, then it must be prepended to the Java value class
name for the anonymous type. If suffix is specified, it must be
appended.
7.7. <class>
Declaration
This binding declaration can be used to customize the binding of a schema component to an element class, value class or interface/implementation class. The customizations can be used to specify:
-
a name for the derived Java class.
-
an alternative implementation of interface/implementation binding.
Specification of an alternate implementation for an interface allows implementations generated by a tool (e.g. based on UML) to be used in place of the default implementation generated by a JAXB provider.
The implementation class may have a dependency upon the runtime of the binding framework. The implementation class may not be portable across JAXB provider implementations. Hence one JAXB provider implementation is not required to support the implementation class from another JAXB provider.
7.7.1. Usage
<class [ name = "className" ]
[ implClass = "implClass" ]
[ ref = "className" ] >
[ <javadoc> ... </javadoc> ]
</class>
-
className
is the name of the derived value class, if specified. It must be a legal Java class name and must not contain a package prefix. The package prefix is inherited from the current value of package. -
implClass
if specified, is the name of the implementation class forclassName
and must include the complete package name. Note that this customization only impacts the return value forclassName
’s factory method. This customization is ignored whennew
is used to create instances of a schema-derived Value class. -
ref
if specified, is the name of the value class that is provided outside the schema compiler. This customization causes a schema compiler to refer to this external class, as opposed to generate a definition. It must include the complete package name. This attribute is mutually exclusive with theclassName
attribute and theimplClass
attribute. -
<javadoc>
element, if specified customizes the Javadoc for the derived value class.<javadoc>
must be specified as described in<javadoc>
Declaration.
7.7.2. Customization Overrides
When binding a schema element’s Java representation to a value class or a Java Element class, the following customization values override the defaults specified in Chapter 5. It is specified in a common section here and referenced from Customizable Schema Elements.
-
name: The name is
className
if specified. -
package name: The name of the package is
packageName
inherited from a scope that covers this schema element.NoteThe
packageName
is only set in the<package>
declaration. The scope ofpackageName
is schema scope and is thus inherited by all schema elements within the schema. -
javadoc: The Javadoc must be generated as specified in section Javadoc Customization. The Javadoc section customized is the
class/interface section
.
7.7.3. Customizable Schema Elements
7.7.3.1. Complex Type Definition
When <class>
customization specified in the
annotation element of the complex type definition, the complex type
definition must be bound to a Java value class as specified in
Java value class applying the
customization overrides as specified in Customization Overrides.
Example: Class Customization: Complex Type Definition To Java value class
XML Schema fragment:
<xs:complexType name="USAddress">
<xs:annotation><xs:appinfo>
<jaxb:class name="MyAddress" />
</xs:appinfo></xs:annotation>
<xs:sequence>...</xs:sequence>
<xs:attribute name="country" type="xs:string"/>
</xs:complexType>
Customized code:
// public class USAddress { // Default Code
public class MyAddress { // Customized Code
public String getCountry() {...}
public void setCountry(String value) {...}
...
}
7.7.3.2. Simple Type Definition
When <class>
customization specified in the
annotation element of a simple type definition, the simple type
definition must be bound to a Java value class as specified in
Bind to a JAXB mapped class applying
the customization overrides as specified in
Customization Overrides.
Example: Class Customization: Simple Type Definition To Java value class
XML Schema fragment:
<xs:simpleType name="SKU">
<xs:annotation><xs:appinfo>
<jaxb:class/>
</xs:appinfo></xs:annotation>
<xs:restriction base=”xs:int”/>
</xs:simpleType>
Customized code:
public class SKU {
@XmlValue
public int getValue() {...}
public void setValue(int value) {...}
...
}
7.7.3.3. Model Group Definition
It is invalid to place a <jaxb:class>
customization on a model group.
7.7.3.5. Global Element Declaration
A <class>
declaration is allowed in the
annotation element of the global element declaration. However, the
implClass
attribute is not allowed. The global element declaration
must be bound as specified in Bind to Element Class
applying the customization overrides specified in
Customization Overrides.
Example: Class Customization: Global Element to Class
XML Schema Fragment:
<xs:complexType name="AComplexType">
<xs:sequence>
<xs:element name="A" type="xs:int"/>
<xs:element name="B" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:element name="AnElement" type="AComplexType">
<xs:annotation><xs:appinfo>
<jaxb:class name="MyElement"/>
</xs:appinfo></xs:annotation>
</xs:element>
Customized code:
// following class is generated because of customization
public class AComplexType {
void setA(int value) {...}
int getA() {...}
void setB(String value) {...}
String getB() {...}
}
public class MyElement extends JAXBElement<AComplexType> {...}
public class ObjectFactory {
// Default code
// JAXBElement<AnElement> createAnElement(AnElement)\{...}
// Customized code
MyElement createMyElement(AnElement) {...}
... other factory methods ...
}
7.7.3.6. Local Element
A local element is a schema element that occurs within a complex type definition. A local element is one of:
-
local element reference (using the “ref” attribute) to a global element declaration.
-
local element declaration (“ref” attribute is not used).
A <class>
declaration is allowed in the
annotation element of a local element. Annotation Restrictions
contains more information regarding the
annotation element for a local element reference. However, the
implClass
attribute is not allowed.
A <class>
customization on local element
reference must result in an invalid customization as specified in
Invalid Customizations since a local
element reference is never bound to a Java Element class.
A <class>
customization on local element
declaration applies only when a local element declaration is bound to a
Java Element class. Otherwise it must result in an invalid customization
as specified in Invalid Customizations.
If applicable, a local element must be bound as
specified in Bind to JAXBElement<T> Instance
applying the customization overrides as specified in
Customization Overrides.
Example: Class Customization: Local Element Declaration To Java Element
The following example is from Examples.
XML Schema fragment:
<xs:complexType name="Base">
<xs:choice maxOccurs="unbounded">
<xs:element name="A" type="xs:string">
<xs:annotation><xs:appinfo>
<jaxb:class name="Bar"/>
</xs:appinfo></xs:annotation>
</xs:element>
<xs:element name="B" type="xs:string"/>
<xs:element name="C" type="xs:int"/>
</xs:choice>
</xs:complexType>
Customized code:
import jakarta.xml.bind.JAXBElement;
public class ObjectFactory {
// element instance factories only
// JAXBElement<String> createBaseA(String value); // default code
JAXBElement<String> createBaseBar(String value); // Customized
JAXBElement<String> createBaseB(String value);
JAXBElement<Integer> createBaseC(Integer value);
}
public class Base {
static public class Bar extends JAXBElement<String> {...} // Customized code
/**
* A general content list that can contain element
* instances of JAXBElement<String> or JAXBElement<Integer>.
*/
List<Object> getBarOrBOrC() {...}
}
7.8. <property>
Declaration
This binding declaration allows the customization of a binding of an XML schema element to its Java representation as a property. This section identifies all XML schema elements that can be bound to a Java property and how to customize that binding.
The scope of customization value can either
be definition scope or component scope depending upon which XML schema
element the <property>
binding declaration is specified.
7.8.1. Usage
<property [ name = "propertyName" ]
[ collectionType = "propertyCollectionType" ]
[ fixedAttributeAsConstantProperty = "true" | "false" | "1" | "0" ]
[ generateIsSetMethod = "true" | "false" | "1" | "0" ]
[ enableFailFastCheck = "true" | "false" | "1" | "0" ]
[ generateElementProperty = "true" | "false" | "1" | "0" ]
[ attachmentRef = "resolve" | "doNotResolve" | "default" ] >
[ <baseType name = "fully qualified Java class"> ... </baseType> ]
[ <javadoc> ... </javadoc> ]
</property>
<baseType name=”fully qualified Java class”>
<javaType> ... </javaType>
</baseType>
For readability, the <baseType>
element is
shown separately. However, it can be used only as a local element within
the <property>
element.
The use of this declaration is subject to the constraints specified in Usage Constraints.
The customization values defined are:
-
name
if specified, defines the customization valuepropertyName;
it must be a legal Java identifier. -
collectionType
if specified, defines the customization valuepropertyCollectionType
which is the collection type for the property.propertyCollectionType
if specified, must be either"indexed"
or 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"
. -
generateIsSetMethod
if specified, defines the customization value ofgenerateIsSetMethod
. The value must be one of"true"
,"false"
,"1"
or"0"
. -
enableFailFastCheck
if specified, defines the customization valueenableFailFastCheck
. The value must be one of"true"
,"false"
,"1"
or"0"
. -
@generateElementProperty
if specified, controls the generation of JAXBElement property. The value must be one of"true"
,"false"
,"1"
or"0"
. The default is absence of the value. It is an error for this attribute to be present if this customization is attached to local or global attribute declarations. This customization affects the binding as follows. It is an error to specify this customization, when the property is required to beJAXBElement
(such as when a property contains multiple elements with different names but of the same type.)-
true : Always generate properties to use
JAXBElement
. -
false : When generating properties from
<element nillable="true" minOccurs="0" />
, generate a property not to use JAXBElement, as if the element declaration were just<element nillable="true"/>
.
-
-
@attachmentRef
has a default value of “default”. This mode defers to default processing as specified in Binding WS-I Attachment Profileref:swaRef
.
When@attachmentRef
value is resolve and the property’s base type is or derives fromxsd:anyURI
, the schema-derived JAXB property has a base type ofjakarta.activation.DataHandler
and the property is annotated with@XmlAttachmentRef
.
Disabling autoresolving an element/attribute of typeref:swaRef
:
When@attachmentRef
value is doNotResolve and the property’s base type derives from standard schema typeref:swaRef
, the schema-derived JAXB property has the base typeString
, derived fromxsd:anyURI
, and@XmlAttachmentRef
is not generated for the property. -
<javadoc>
element, if specified customizes the Javadoc for the property’s getter method.<javadoc>
must be specified as described in<javadoc>
Declaration.
7.8.2. baseType
The <baseType>
element is intended to allow
the customization of a base type for a JAXB property. This element can
only be a child of <jaxb:property> element.
<baseType name="fully qualified Java class>">
<javaType> ... </javaType>
</baseType>
The @name
attribute enables either the
specialization or generalization of the default base type binding for a
JAXB property. Child element <javaType>
is used to convert the default
base type to a Java class. These two mutual exclusive usages of the
<baseType> customization are described below.
7.8.2.1. Conversion using Child element <javaType>
Optional child element <javaType>
, if
specified, defines the customization value javaType
and must be
specified as defined in <javaType>
Declaration.
The customization value defined has component scope. This
customization converts the default base type’s value for a simple type
definition to the Java class specified by <javaType> name.
The schema-derived JAXB property is annotated
with @XmlJavaTypeAdapter
specified in Section 8.
@XmlJavaTypeAdapter.value()
is set to a generated
class[27] that extends
jakarta.xml.bind.annotation.adapter.XmlAdapter
. The generated class’
unmarshal
method must call the <javaType> customization’s parse
method, which is specified in <<javaType>
Declaration.
The generated class’ marsha
method must call
the <javaType> customization’s print method.
7.8.2.2. Generalize/Specialize baseType with attribute @name
The name
attribute for`<baseType` enables
more precise control over the actual base type for a JAXB property. This
customization enables specifying an alternative base type than the
property’s default base type. The alternative base type must still be in
the same class inheritance hierarchy as the default base type. The
alternative base type must be either a super interface/class or subclass
of the default Java base type for the property. The customization
enables one to specialize or generalize the properties binding.
The name
attribute value must be a fully
qualified Java class name. When the default base type is a primitive
type, consider the default Java base type to be the Java wrapper class
of that primitive type.
Generalizing the basetype using this
customization enables simple type substitution for a JAXB property
representing with too restrictive of a default base type. To enable all
possible valid type substitutions, the name
attribute should be
java.lang.Object
. However, if for example, it is known that all type
substitutions will share a more specific Java super interface/class than
java.lang.Object
, that Java class name can be used achieve a stronger
typed binding. With this customization, the JAXB annotation generated
for the property’s @XmlElement.type()
or @XmlAttribute.type()
is
still the default Java datatype for the element/attribute’s
schema-defined type.
The schema-derived customized JAXB property
is annotated, either explicitly or by default mapping annotations, with
the mapping annotation @XmlElement
, specified in Section 8.10.1. The
@XmlElement
annotation element type is derived in terms of the
abstract model properties for a element type definition summarized in
Element Declaration Schema Component
as follows:
@XmlElement element | @XmlElement value |
---|---|
type |
the java type binding of the element declaration’s {type definition} |
Note that the Java class for
@XmlElement.type()
can differ from the recommended JAXB property’s
base type to enable type substitution of java.lang.Object. This binding
enables unmarshalling of the Element’s simple content when it is not
qualified with an xsi:type
as the element’s schema-declared type.
@XmlElement.type()
acts as the default xsi:type
for a JAXB property
where the property’s base type was generalized to allow for type
substitution of an element declaration with a simple type definition.
Specializing the basetype using this
customization generates stronger typing than default JAXB binding. For
example, an XML element or attribute of xs:IDREF
binds to
java.lang.Object
by default as specified in
Binding an IDREF component to a Java property.
If the schema only intends the reference to be to an element
that binds to a specific type, the baseType @name schema customization
can be used to specialize the binding.
Example: Specialize binding of an IDREF via customization
Given XML Schema fragment:
<xs:complexType name="Book">
<xs:sequence>
<xs:element name="author" type="xs:IDREF"/>
<xs:annotation><xs:appinfo>
<jaxb:property>
<jaxb:baseType name=”AuthorBio.class”/>
</jaxb:property>
</xs:appinfo></xs:annotation>
<!-- ... -->
</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
AuthorBio getAuthor() {...}
void setAuthor(AuthorBio referencedObj) {...}
}
public class AuthorBio {
@XmlID
String getName() {...}
void setName(String value) {...}
}
7.8.2.3. Usage Constraints
The usage constraints on <property>
are
specified below. Any constraint violation must result in an invalid
customization as specified in Invalid Customizations. The usage constraints are:
-
The
<baseType>
is only allowed with the following XML schema elements from the Customizable Schema Elements:-
Local Element, Local Element.
-
Local Attribute, Local Attribute.
-
ComplexType with simpleContent, ComplexType.
-
-
<baseType>
can either have a name attribute or a<javaType>
, they both can not exist at the same time. -
The
fixedAttributeAsConstantProperty
is only allowed with a local attribute, Local Attribute, that is fixed. -
If a
<property>
declaration is associated with the<complexType>
, then a<property>
customization cannot be specified on the following schema elements that are scoped to<complexType>
:-
Local Element
-
Model group
-
Model Group Reference
The reason is that a
<property>
declaration associated with a complex type binds the content model of the complex type to a general content property. If a<property>
declaration is associated with a schema element listed above, it would create a conflicting customization. -
Design Note
A Local Attribute is excluded from the list above. The reason is that a local attribute is not part of the content model of a complex type. This allows a local attribute to be customized (using a <property> declaration) independently from the customization of a complex type’s content model. |
Example: Property Customization: simple type customization
<xs:complexType name="internationalPrice">
....
<xs:attribute name="currency" type="xs:string">
<xs:annotation><xs:appinfo>
<jaxb:property>
<jaxb:baseType>
<jaxb:javaType name="java.math.BigDecimal"
parseMethod="jakarta.xml.bind.DatatypeConverter.parseInteger"
printMethod="jakarta.xml.bind.DatatypeConverter.printInteger"/>
</jaxb:baseType>
</jaxb:property>
</xs:appinfo></xs:annotation>
</xs:attribute>
</xs:complexType>
The code generated is:
public class InternationalPrice {
// String getCurrency(); default
java.math.BigDecimal getCurrency() {...} //customized
public void setCurrency(java.math.BigDecimal val) {...} // customized
}
7.8.3. Customization Overrides
When binding a schema element’s Java representation to a property, the following customization values override the defaults specified in Chapter 6. It is specified in a common section here and referenced from Customizable Schema Elements.
-
name: If propertyName is defined, then it is the name obtained by mapping the name as specified in Customized Name Mapping.
-
base type: The basetype is
propertyBaseType
if defined. The propertyBaseType is defined by a XML schema element in Customizable Schema Elements. -
collection type: The collection type is
propertyCollectionType
if specified; otherwise it is thepropertyCollectionType
inherited from a scope that covers this schema element. -
javadoc: The Javadoc must be generated as specified in section Javadoc Customization. The Javadoc section customized is the
method section
. -
If
propertyBaseType
is a Java primitive type andpropertyCollectionType
is a class that implementsjava.util.List
, then the primitive type must be mapped to its wrapper class.
The following does not apply if local attribute is being bound to a constant property as specified in Local Attribute:
-
If
generateIsSetMethod
is"true"
or"1"
, then additional methods as specified inisSet
Property Modifier must be generated. -
If
enableFailFastCheck
is"true"
or"1"
, then the type constraint checking when setting a property is enforced by the JAXB implementation. Support for this feature is optional for a JAXB implementation in this version of the specification.
7.8.4. Customizable Schema Elements
7.8.4.1. Global Attribute Declaration
A <property>
declaration is allowed in
the annotation element of the global attribute declaration.
The binding declaration does not bind the global attribute declaration to a property. Instead it defines customization values that have definition scope. The definition scope covers all local attributes (Local Attribute) that can reference this global attribute declaration. This is useful since it allows the customization to be done once when a global attribute is defined instead of at each local attribute that references the global attribute declaration.
7.8.4.2. Local Attribute
A local attribute is an attribute that occurs within an attribute group definition, model group definition or a complex type. A local attribute can either be a
-
local attribute reference (using the “ref” attribute) to a global attribute declaration.
-
local attribute declaration (“ref” attribute is not used).
A <property>
declaration is allowed in
the annotation element of a local
attribute. Annotation Restrictions
contains more information regarding the annotation element for a local
attribute reference. The customization values must be defined as
specified in Usage and have component
scope.
If javaType
is defined, then the
propertyBaseType
is defined to be Java datatype specified in the
"name"
attribute of the javaType
.
-
If
fixedAttributeAsConstantProperty
is"true"
or"1"
and the local attribute is a fixed, the local attribute must be bound to a Java Constant property as specified in Bind to a Java Constant property applying customization overrides as specified in Customization Overrides. ThegenerateIsSetMethod
,choiceContentProperty
andenableFailFastCheck
must be considered to have been set to"false"
. -
Otherwise, it is bound to a Java property as specified in Attribute use applying customization overrides as specified in Customization Overrides.
Example: Customizing Java Constant Property
XML Schema fragment:
<xs:complexType name="USAddress">
<xs:attribute name="country" type="xs:NMTOKEN" fixed="US">
<xs:annotation><xs:appinfo>
<jaxb:property name="MY_COUNTRY"
fixedAttributeAsConstantProperty="true"/>
</xs:appinfo></xs:annotation>
</xs:attribute>
</xs:complexType>
Customized derived code:
public class USAddress {
public static final String MY_COUNTRY = "US"; // Customized Code
}
Example 2: Customizing to other Java Property
XML Schema fragment:
<xs:complexType name="USAddress"> +
<xs:attribute name="country" type="xs:string">
<xs:annotation><xs:appinfo>
<jaxb:property name="MyCountry"/>
</xs:appinfo></xs:annotation>
</xs:attribute>
</xs:complexType>
Customized derived code:
public class USAddress {
// public getString getCountry(); // DefaultCode
// public void setCountry(string value);//Default Code
public String getMyCountry() {...} //Customized Code
public void setMyCountry(String value) {...}// Customized Code
}
Example 3: Generating IsSet Methods
XML Schema fragment:
<xs:attribute name="account" type = "xs:int">
<xs:annotation><xs:appinfo>
<jaxb:property generateIsSetMethod="true"/>
</xs:appinfo></xs:annotation>
</xs:attribute>
Customized code:
public int getAccount();
public void setAccount(int account);
public boolean isSetAccount(); // Customizedcode
public void unsetAccount(); // Customizedcode
7.8.4.3. Global Element Declaration
A <property>
declaration is allowed in the
annotation element of a global element declaration. However, the usage
is constrained as follows:
The binding declaration does not bind the global element declaration to a property. Instead it defines customization values that have definition scope. The definition scope covers all local elements (Local Element) that can reference this global element declaration. This is useful since it allows the customization to be done once when a global element is defined instead of at each local element that references the global element declaration.
7.8.4.4. Local Element
A local element is a schema element that occurs within a complex type definition. A local element is one of:
-
local element reference (using the “ref” attribute) to a global element declaration.
-
local element declaration (“ref” attribute is not used).
A <property>
declaration is allowed in the
annotation element of a local element. Annotation Restrictions
contains more information regarding the
annotation element for a local element reference.
The customization values must be defined as specified in Usage and have component scope.
If javaType
is defined, then the
propertyBaseType
is defined to be Java datatype specified in the
"name"
attribute of the javaType
.
The local element must be bound as specified in Content Model Default Binding applying customization overrides as specified in Customization Overrides.
See example in Example 3 in section Model Group.
7.8.4.5. Wildcard
A <property>
declaration is allowed in the
annotation element of the wildcard schema component. The customization
values must be defined as specified in Usage and have component scope.
The wildcard schema component must be bound to a property as specified in Bind wildcard schema component applying customization overrides as specified in Customization Overrides.
Example: The following schema example is from UDDI V2.0
<xs:complexType name="businessEntityExt">
<xs:sequence>
<xs:any namespace="##other"
processContents="strict"
minOccurs="1" maxOccurs="unbounded">
<xs:annotation><xs:appinfo>
<jaxb:property name="Extension"/>
</xs:appinfo></xs:annotation>
</xs:any>
....
</xs:sequence>
</xs:complexType>
Customized derived code:
public class BusinessEntityExt {
...
// List getAny(); // Default Code
List getExtension() {...} // Customized Code
}
7.8.4.6. Model Group
A <property>
binding declaration is allowed
in the annotation element of the compositor (i.e. <choice>
,
<sequence>
or <all>
). The customization values must be defined as
specified in Usage and have component
scope.
The customized binding of a model group is determined by the following:
-
choiceContentProperty
attribute in<globalBindings>
.-
If propertyBaseType is defined and a
<property>
declaration is also present, then the customization overrides specified in Customization Overrides must be applied by the model group’s parent schema element to the property used to aggregate the Java value class. -
If propertySet is defined, then the model group’s parent schema element must aggregate the property set as specified in Aggregation of Property Set.
-
XML Schema fragment
<xs:annotation><xs:appinfo>
<jaxb:globalBindings choiceContentProperty="true"/>
</xs:appinfo></xs:annotation>
<xs:complexType name=”AType”>
<xs:choice>
<xs:element name="foo" type="xs:int"/>
<xs:element name="bar" type="xs:string"/>
</xs:choice>
</xs:complexType>
Customized derived code:
class ObjectFactory {
JAXBElement<Integer> createAtypeFoo(Integer value);
JAXBElement<String> createAtypeBar(String value);
}
public class AType {
void setFooOrBar(Object o) {...} //customized code
Object getFooOrBar() {...} //customized code
}
The choiceContentProperty
is required to
bind the choice model group to a choice content property.
XML Schema fragment:
<xs:complexType name="Base">
<xs:choice maxOccurs="unbounded">
<xs:annotation><xs:appinfo>
<jaxb:property name="items" />
</xs:appinfo></xs:annotation>
<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>
Customized derived code:
public class Base {
/**
* A general content list that can contain
* instances of Base.A, Base.B and Base.C.
*/
// List getAOrBOrC(); - default
List getItems() {...} // Customized Code
}
XML Schema fragment:
<xs:complexType name="USAddress"/>
<xs:complexType name="PurchaseOrderType">
<xs:sequence>
<xs:choice>
<xs:group ref="shipAndBill"/>
<xs:element name="singleUSAddress" type="USAddress">
<xs:annotation><xs:appinfo>
<jaxb:property name="address"/>
</xs:appinfo></xs:annotation>
</xs:element>
</xs:choice>
</xs:sequence>
</xs:complexType>
<xs:group name="shipAndBill">
<xs:sequence>
<xs:element name="shipTo" type="USAddress">
<xs:annotation><xs:appinfo>
<jaxb:property name="shipAddress"/>
</appinfo></annotation>
</xs:element>
<xs:element name="billTo" type="USAddress">
<xs:annotation><xs:appinfo>
<jaxb:property name="billAddress"/>
</xs:appinfo></xs:annotation>
</xs:element>
</xs:sequence>
</xs:group>
Customized derived code:
public interface PurchaseOrderType {
USAddress getShipAddress(); void setShipAddress(USAddress);
USAddress getBillAddress(); void setBillAddress(USAddress);
USAddress getAddress(); void setAddress(USAddress);
}
7.8.4.7. Model Group Reference
A model group reference is a reference to a
model group using the ref
attribute. A property customization is
allowed on the annotation property of the model group reference. Section
Annotation Restrictions contains more
information regarding the annotation element for a model group
reference.
The customization values must be defined as specified in Usage and have component scope. A model group reference is bound to a Java property set or a list property as specified in Content Model Default Binding applying customization overrides as specified in Customization Overrides.
7.8.4.8. ComplexType
A <property>
customization is allowed on
the annotation element of a complex type. The customization values must
be defined as specified in Usage and
have component scope. The result of this customization depends upon the
content type of the complex type.
-
If the content type of the content model is simple content, then the content model must be bound to a property as specified in Simple Content Binding. applying the customization overrides as specified in Customization Overrides. If
javaType
is defined, then thepropertyBaseType
is defined to be Java datatype specified in the"name"
attribute of thejavaType
. -
For all other content types, the content model must be bound as specified in step 1. of Content Model Default Binding applying the customization overrides as specified in Customization Overrides.
Design Note
The <property> declaration is not allowed on an annotation element of attribute group definition. However, attributes within the attribute group definition can themselves be customized as described in the “Local Attribute” section above. Section 7.8.4.2, “Local Attribute.” |
7.9. <javaType>
Declaration
A <javaType>
declaration provides a way to
customize the binding of an XML schema atomic datatype to a Java
datatype, referred to as the target Java datatype. The target Java
datatype can be a Java built-in data type or an application specific
Java datatype. This declaration also provides two additional methods:
a parse method and a print method.
The parse method converts a lexical representation of the XML schema datatype into a value of the target Java datatype. The parse method is invoked by a JAXB provider’s implementation during unmarshalling.
The print method converts a value of the target Java datatype into its lexical representation of the XML schema datatype. The print method is invoked by a JAXB provider’s implementation during marshalling.
7.9.1. Usage
<javaType name="javaType"
[ xmlType = "xmlType" ]
[ parseMethod = "parseMethod" ]
[ printMethod = "printMethod" ]>
The binding declaration can be used in one of the following:
-
a
<globalBindings>
declaration. -
annotation element of one of the XML schema elements specified in Customizable Schema Elements.
-
in a
<property>
declaration. See<property>
Declaration. This can be used for customization at the point of reference to a simple type.
When used in a <globalBindings>
declaration, <javaType>
defines customization values with global
scope. When used in an annotation element of one of the schema elements
specified in Customizable Schema Elements
the customization values have component scope.
7.9.1.1. name
The javaType
, if specified, is the Java
datatype to which xmlType
is to be bound. Therefore, javaType
must
be a legal Java type name, which may include a package prefix. If the
package prefix is not present, then the Java type name must be one of
the Java built-in primitive types [JLS - Java Language Specification,
Second Edition, Section 4.2, “Primitive Types and Values”]. (For
example, "int"
) or a Java class in the unnamed package. If class
javaType declares a public constructor with following signature,
javaType(java.lang.String)
, parseMethod
attribute does not need to
be specified.
7.9.1.2. xmlType
The xmlType
, if specified, is the name of
the XML Schema datatype to which javaType
is to bound. If specified,
xmlType
must be a XML atomic datatype derived from restriction. The
use of the xmlType
is further constrained as follows.
The purpose of the xmlType
attribute is to
allow the global customization of a XML schema to Java datatype. Hence
xmlType
attribute is required when <javaType>
declaration’s parent
is <globalBindings>
. If absent, it must result in an invalid
customization as specified in Invalid Customizations.
Otherwise, the xmlType attribute must not be present
since the XML datatype is determined from the XML schema element with
which the annotation element containing <javaType>
declaration or the
<baseType>
(containing the <javaType>
) is associated. If present,
it must result in an invalid customization as specified in
Invalid Customizations.
Examples can be found in javaType Customization: Java Built-in Type and javaType Customization: User Specified Parse Method
7.9.1.3. parseMethod
The parse method if specified, must be applied during unmarshalling in order to convert a string from the input document into a value of the target Java datatype. The parse method must be invoked as follows:
-
The parse method defaults to
new
providedjavaType
is not a Java primitive type such as ("int"
). IfjavaType
is a Java primitive type, then this must result in an invalid customization as specified in Invalid Customizations. Otherwise, the binding compiler must assume that the target type is a class that defines a constructor as follows:-
String
as the first parameter of the constructor.
To apply the conversion to a string it must generate code that invokes this constructor, passing it the input string.
-
-
The parse method may be specified in the form ClassName.methodName, where the ClassName is a fully qualified class name that includes the package name. A compiler must assume that the class ClassName exists and that it defines a static method named methodName that takes:
-
String
as the first argument.
To apply the conversion to a string it must generate code that invokes this method, passing it the input string.
-
-
The parse method may be specified in the form methodName provided
javaType
is not a Java primitive type (such as"int"
). IfjavaType
is Java primitive type, then this must result in an invalid customization as specified in Invalid Customizations. Otherwise, the binding compiler must assume that methodName is a method in the classjavaType
. The binding compiler must therefore prefix thejavaType
to the methodName and processjavaType
.methodName as specified in above.
The string passed to parse method can be any
lexical representation for xmlType
as specified in [XSD PART2].
If parseMethod attribute is not specified,
xmlType
is not a primitive or wrapper class and javaType
has an
accessible one argument constructor, where the argument is type
java.lang.String
, input text is parsed by invoking new
with a
java.lang.String
parameter.
7.9.1.4. printMethod
The print method if specified, must be applied during marshalling in order to convert a value of the target type into a lexical representation:
-
The print method is specified in the form methodName provided
javaType
is not a Java primitive type (such as"int"
). IfjavaType
is Java primitive type, then this must result in an invalid customization as specified in Invalid Customizations. Otherwise, the compiler must assume that the target type is a class or an interface that defines a zero-argument instance method named methodName that returns aString
. To apply the conversion it must generate code to invoke this method upon an instance of the target Java datatype. -
If the print method is specified in the form ClassName.methodName then the compiler must assume that the class ClassName exists and that it defines a static method named methodName that returns a string that takes the following:
-
the first parameter is the target Java datatype.
To apply the conversion to a string it must generate code that invokes this method, passing it a value of the target Java datatype.
-
The lexical representation to which the value
of the target type is converted can be any lexical representation for
xmlType
as specified in [XSD PART2].
If printMethod
attribute is not specified
and xmlType
is not a primitive or wrapper class, javaType.toString()
is used as the default print method..
7.9.2. DatatypeConverter
Writing customized parse and print methods
can be difficult for a Java programmer. This requires a programmer to
understand the lexical representations of XML schema datatypes. To make
it easier, an interface, DatatypeConverterInterface
, and a class
DatatypeConverter
are defined to expose the parse and print methods of
a JAXB implementation. These can be invoked by user defined parse and
print methods. This shifts the burden of dealing with lexical spaces
back to the JAXB implementation.
The DatatypeConverterInterface
defines
parse and print methods for XML schema datatypes. There is one parse and
print method for each of XML schema datatype specified in
Java Mapping for XML Schema Built-in Types. The interface is fully specified by the Javadoc specified in
jakarta.xml.bind.DatatypeConverterInterface
.
The DatatypeConverter
class defines a
static parse and print method corresponding to each parse and print
method respectively in the DatatypeConverterInterface
interface. The
property jakarta.xml.bind.DatatypeConverter
can be used to select the
name of a class that provides an implementation of the parse and print
methods. The name specified in the property must be a fully qualified
class name and must implement the interface DatatypeConverterInterface
. The class is fully specified by the Javadoc specified in
jakarta.xml.bind.DatatypeConverter
.
7.9.2.1. Usage
The following example demonstrates the use of
the DatatypeConverter
class for writing a customized parse and print
method.
This example shows the binding of XML schema
type "xs:date"
is bound to a Java datatype long
using user specified
print and parse methods.
<jaxb:globalBindings>
<jaxb:javaType name="long" xmlType="xs:date"
parseMethod="pkg.MyDatatypeConverter.myParseDate"
printMethod="pkg.MyDatatypeConverter.myPrintDate"/>
</jaxb:javaType>
</jaxb:globalBindings>
package pkg;
import jakarta.xml.bind.DatatypeConverter;
public class MyDatatypeConverter {
public static long myParseDate(String s) {
java.util.Calendar d = DatatypeConverter.parse(s);
long result= cvtCalendarToLong(d) ; // userdefined method
return result;
}
public static String myPrintDate(long l) {
java.util.Calendar d = cvtLongToCalendar(l);//user defined
return DatatypeConverter.print(d);
}
}
The implementation of the print methods (
parseDate
and printDate
) are provided by the user.
The customization is applied during the
processing of XML instance document. During unmarshalling, the JAXB
implementation invokes myParseDate
. If myParseDate
method throws a
ParseException
, then the JAXB implementation code catches the
exception, and generate a parseConversionEvent
.
7.9.2.2. Lexical And Value Space
[XSD PART 2] specifies both a value space and a lexical space for an schema datatypes. There can be more than one lexical representation for a given value.
Examples of multiple lexical representations for a single value are:
-
For boolean, the value
true
has two lexical representations"true"
and"1"
. -
For integer, the value
1
has two lexical representations"1.0"
and"1"
.
XSD PART 2 also specifies a canonical representation for all XML schema atomic datatypes.
The requirements on the parse and print methods are as follows:
-
A JAXB implementation of a parse method in
DatatypeConverterInterface
must be capable of a processing all lexical representations for a value as specified by [XSD PART 2]. This ensures that an instance document containing a value in any lexical representation specified by [XSD PART 2] can be marshalled. -
A JAXB implementation of a print method in
DatatypeConverterInterface
must convert a value into any lexical representation of the XML schema datatype to which the parse method applies, as specified by [XSD PART 2] and which is valid with respect to the application’s schema.
Design Note
The print methods that are exposed may not be portable. The only requirement on a print method is that it must output a lexical representation that is valid with respect to the schema. So two vendors can choose to output different lexical representations. However, there is value in exposing them despite being non portable. Without the print method, a user would have to be knowledgeable about how to output a lexical representation for a given schema datatype, which is not desirable. |
7.9.3. Built-in Conversions
As a convenience to the user, this section specifies some built-in conversions. A built-in conversion is one where the parse and the print method may be omitted by a user. The built-in conversions leverage the narrowing and widening conversions defined in [JLS - Java Language Specification, Second Edition], Section 5.1.2, “Widening Primitive Conversion” and Section 5.1.3, “Narrowing Primitive Conversions.” For example:
<xs:simpleType name="foo" type="xs:long">
<xs:annotation><xs:appinfo>
<jaxb:javaType name="int"/>
</xs:appinfo></xs:annotation>
</xs:simpleType>
If the parse method is omitted, then a JAXB implementation must perform the one of the following binding options:
-
If
javaType
is one of the following primitive types or its corresponding wrapper classbyte
,short
,int
,long
,float
,double
, bindxmlType
to its default Java datatype using the parse method for thexmlType
defined inDatatypeConverter
. If necessary, convert the default Java datatype forxmlType
to value of typejavaType
by a type cast. -
Else if default Java datatype defines a public one-argument constructor that takes a
java.lang.String
, usenew
with ajava.lang.String
parameter for parsing. -
Else javaType(java.lang.String) does not exist, this must result in an invalid binding customization as specified in Invalid Customizations.
This example illustrates how to bind a XML schema type to a Java type different from the default one.
XML Schema fragment:
<xs:element name="partNumber" type="xs:int"/>
Customization:
<jaxb:globalBindings>
....
<jaxb:javaType name="long"
xmlType="xs:int"/>
</jaxb:globalBindings>
Since a Java built-in is specified, a parse
or a print method need not be specified. A JAXB implementation uses the
parse and print methods defined in DatatypeConverter
class for
converting between lexical representations and values. A JAXB
implementation unmarshals an input value using the following methods:
int j = (int) DataTypeConverter.parseLong(string);
7.9.4. Events
The parse method parseMethod
may fail,
since it is only defined on those strings that are valid representations
of target Java datatype values and it can be applied to arbitrary
strings. A parse method must indicate failure by throwing an exception
of whatever type is appropriate, though it should never throw a
TypeConstraintException
. A JAXB unmarshaller process must ensure that
an exception thrown by a parse method is caught and, if appropriate, a
parseConversionEvent
event is generated.
The print method printMethod
usually does
not fail. If it does, then the JAXB implementation must ensure that the
exception thrown by a print method is caught and a
printConversionEvent
is generated.
7.9.5. Customization Overrides
The <javaType>
overrides the default
binding of xmlType
to the Java datatype specified in Java Mapping for XML Schema Built-in Types.
7.9.7. Simple Type Definition
A <javaType>
binding declaration is allowed
in the annotation element of the of a simple type definition. The
javaType
overrides the default binding of xmlType
to the Java
datatype specified in Java Mapping for XML Schema Built-in Types. The customization values defined have
definition scope and thus covers all references to this simple type
definition.
If the simple type definition is mapped to a
schema-derived type, an @XmlJavaTypeAdapter
is generated on that
class. Annotation element @XmlJavaTypeAdapter.value()
is set to a
generated class[28] that extends
jakarta.xml.bind.annotation.adapter.XmlAdapter
. The generated class’
unmarshal
method must call the <javaType> customization’s parse
method, which is specified in <javaType>
Declaration.
The generated class’ marshal
method must call
the <javaType> customization’s print method.
7.9.7.1. GlobalBindings
A <javaType>
binding declaration is allowed
as part of <globalBindings>
. The javaType
overrides the default
binding of xmlType
to the Java datatype specified in Java Mapping for XML Schema Built-in Types.
The customization values defined have global scope.
For each element or attribute declaration
that references an xmlType
that has a globalBindings <javaType>
customization specified for it, the corresponding JAXB property is
annotated with @XmlJavaTypeAdapter
.
7.9.7.2. <property><baseType>
declaration
A <javaType>
binding declaration is allowed
as part of <baseType>
in the <property>
binding declaration. The
javaType
overrides the default binding of xmlType
to the Java
datatype specified in Java Mapping for XML Schema Built-in Types. Additional semantics are specified in
basetype also apply.
The schema-derived JAXB property is annotated
with @XmlJavaTypeAdapter
as specified in
baseType.
7.10. <typesafeEnum>
Declaration
This binding declaration allows the customization of a binding of an XML schema element to its Java representation as an enum type, Section 8.9 in [JLS3]. Only simple type definitions with enumeration facets can be customized using this binding declaration.
7.10.1. Usage
<typesafeEnumClass>
[ name = "enumClassName" ]
[ map = "true" | "false" | "1" | "0" ]
[ ref = "enumClassName" ]
[ <typesafeEnumMember> ... </typesafeEnumMember> ]*
[ <javadoc> enumClassJavadoc </javadoc> ]
</typesafeEnumClass>
<typesafeEnumMember name = "enumMemberName">
[ value = "enumMemberValue"]
[ <javadoc> enumMemberJavadoc </javadoc> ]
</typesafeEnumMember>
There are two binding declarations
<typesafeEnumClass>
and <typesafeEnumMember>
. The two binding
declarations allow the enumeration members of an enumeration class and
enumeration class itself to be customized independently.
The <typesafeEnumClass>
declaration
defines the following customization values:
-
name
defines the customization valueenumClassName
, if specified.enumClassName
must be a legal Java Identifier; it must not have a package prefix.
For an anonymous simple type, thename
attribute must be present. If absent, it must result in an invalid customization as specified in Invalid Customizations. -
map
determines if the simple type definition should be bound to an enum type. Whenmap
’s value isfalse
, then the simple type definition must not be bound to an enum type.map
defaults totrue
. -
ref
if specified, is the name of the enum class that is provided outside the schema compiler. This customization causes a schema compiler to refer to this external enum, as opposed to generate a definition. It must include the complete package name. This attribute is mutually exclusive with theclassName
attribute and themap
attribute. -
<javadoc>
element, if specified customizes the Javadoc for the enumeration class. <javadoc> defines the customization valueenumClassjavadoc
if specified as described in<javadoc>
Declaration. -
Zero or more
<typesafeEnumMember>
declarations. The customization values are as defined as specified by the<typesafeEnumMember>
declaration.
The <typesafeEnumMember>
declaration
defines the following customization values:
-
name
must always be specified and defines a customization valueenumMemberName
.enumMemberName
must be a legal Java identifier. -
value
defines a customization valueenumMemberValue
, if specified.enumMemberValue
must be the enumeration value specified in the source schema. The usage ofvalue
is further constrained as specified invalue
Attribute. -
<javadoc>
if specified, customizes the Javadoc for the enumeration constant.<javadoc>
defines a customization valueenumMemberjavadoc
if specified as described in<javadoc>
Declaration.
For inline annotation, the
<typesafeEnumClass>
must be specified in the annotation element of the
<simpleType>
element. The <typesafeEnumMember>
must be specified
in the annotation element of the enumeration member. This allows the
enumeration member to be customized independently from the enumeration
class.
7.10.2. value
Attribute
The purpose of the value attribute is to
support customization of an enumeration value using an external binding
syntax. When the <typesafeEnumMember>
is used in an inline annotation,
the enumeration value being customized can be identified by the
annotation element with which it is associated. However, when an
external binding declaration is used, while possible, it is not
desirable to use XPath to identify an enumeration value.
So when customizing using external binding
syntax, the value
attribute must be provided. This serves as a key to
identify the enumeration value to which the <typesafeEnumMember>
applies. It’s use is therefore further constrained as follows:
-
When
<typesafeEnumMember>
is specified in the annotation element of the enumeration member or when XPath refers directly to a single enumeration facet, then the value attribute must be absent. If present, it must result in must result in an invalid customization as specified in Invalid Customizations. -
When
<typesafeEnumMember>
is scoped to thetypesafeEnumClass
declaration, the value attribute must be present. If absent, it must result in must result in an invalid customization as specified in Invalid Customizations. The enumMemberValue must be used to identify the enumeration member to which the<typesafeEnumMember>
applies.
An example of external binding syntax can be found in Example 2.
7.10.3. Inline Annotations
There are two ways to customize an enumeration class:
-
split inline annotation
-
combined inline annotation
In split inline annotation, the enumeration
value and the enumeration class are customized separately i.e. the
<typesafeEnumMember>
is used independently not as a child element of
<typesafeEnumClass>
. An example of this is shown in Example 1.
In combined inline annotation, the
enumeration value and the enumeration class are customized together i.e.
the <typesafeEnumMember>
is used as a child element of
<typesafeEnumClass>
. This is similar to the customization used in
external binding declaration. In this case the value
attribute must be
present in the <typesafeEnumMember>
for reasons noted in
value
Attribute. An example of this
customization is shown in Example 3.
7.10.4. Customization Overrides
When binding a schema type definition’s Java representation to an enum type, the following customization values override the defaults specified in Chapter 5. It is specified in a common section here and referenced from Customizable Schema Elements.
-
name: If enumClassName is defined, then the name obtained by mapping enumClassName as specified in Customized Name Mapping.
-
package name: The name obtained by inheriting
packgeName
from a scope that covers this schema element and mapping packageName as specified in Customized Name Mapping. -
enumclass javadoc:
enumClassJavaDoc
if defined, customizes theclass/interface section
(Javadoc Sections) for the enumeration class, as specified in Javadoc Customization. -
enum constant set: Each member of the set is computed as follows:
-
name: If enumMemberName is defined, the name obtained by mapping enumMemberName as specified in Customized Name Mapping.
-
javadoc:
enumMemberJavaDoc
if defined, customizes thefield section
(Javadoc Sections) for the enumeration class, as specified in Javadoc Customization.
-
7.10.5. Customizable Schema Elements
Any XML Schema simple type which has an
enumeration facet can be customized with <jaxb:typesafeEnumClass>
declaration with the following exception. If the simple type definition
derives from 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
, it must result
in an invalid customization as specified in
Invalid Customizations. Since most
of these Xml datatypes bind to a mutable Java type, instances of these
Java types are not sufficient to be an immutable value of an enum
constant.
Design Note
The rationale for not allowing a type definition that derives from |
XML Schema fragment:
<xs:simpleType name="USState">
<xs:annotation><xs:appinfo>
<jaxb:typesafeEnumClass name="USStateAbbr"/>
</xs:appinfo></xs:annotation>
<xs:restriction base="xs:NCName">
<xs:enumeration value="AK">
<xs:annotation><xs:appinfo>
<jaxb:typesafeEnumMember name="STATE_AK"/>
</xs:appinfo></xs:annotation>
</xs:enumeration>
<xs:enumeration value="AL">
<xs:annotation><xs:appinfo>
<jaxb:typesafeEnumMember name="STATE_AL"/>
</xs:appinfo></xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
Customized derived code:
public enum USStateAbbr {
STATE_AL, STATE_AK;
public String value() { return name(); }
public static USStateAbbr fromValue(String value) {...}
};
The following example shows how to customize the above XML schema fragment using an external binding syntax.
<jaxb:typesafeEnumClass name="USStateAbbr">
<jaxb:typesafeEnumMember name="STATE_AK" value="AK"/>
<jaxb:typesafeEnumMember name="STATE_AL" value="AL"/>
</jaxb:typesafeEnumClass>
The attribute value
must be specified for
<typesafeEnumMember>
. This identifies the enumeration member to which
<typesafeEnumMember>
applies.
The following example shows how to customize the above XML schema fragment using inline annotation which does not split the external binding syntax.
<xs:simpleType name="USState">
<xs:annotation><xs:appinfo>
<jaxb:typesafeEnumClass name="USStateAbbr">
<jaxb:typesafeEnumMember name="STATE_AK" value="AK"/>
<jaxb:typesafeEnumMember name="STATE_AL" value="AL"/>
</jaxb:typesafeEnumClass>
</xs:appinfo></xs:annotation>
<xs:restriction base="xs:NCName">
<xs:enumeration value="AK"/>
<xs:enumeration value="AL"/>
</xs:restriction>
</xs:simpleType>
The attribute value must be specified for
typesafeEnumMember
. This identifies the enumeration member to which
the binding declaration applies.
7.11. <javadoc>
Declaration
The <javadoc>
declaration allows the
customization of a javadoc that is generated when an XML schema
component is bound to its Java representation.
This binding declaration is not a global XML element. Hence it can only be used as a local element within the content model of another binding declaration. The binding declaration in which it is used determines the section of the Javadoc that is customized.
7.11.1. Javadoc Sections
The terminology used for the javadoc sections
is derived from “Requirements for Writing Java API Specifications” which
can be found online at https://www.oracle.com/java/technologies/javase/api-specifications.html
.
The following sections are defined for the purposes for customization:
-
package section (corresponds to package specification)
-
class/interface section (corresponds to class/interface specification)
-
method section (corresponds to method specification)
-
field section (corresponds to field specification)
7.11.2. Usage
Note that the text content of a <javadoc>
element must use CDATA
or <
to escape embedded HTML tags.
<javadoc>
Contents in <b>Javadoc<\b> format.
</javadoc>
or
<javadoc>
<<![CDATA[
Contents in <b>Javadoc<\b> format
]]>
</javadoc>
7.11.3. Javadoc Customization
The Javadoc must be generated from the
<javadoc>
element if specified. The Javadoc section depends upon where
<javadoc>
element is used. JAXB providers may generate additional
provider specific Javadoc information (for example, contents of the
<xs:documentation>
element).
7.12. <dom>
Declaration
The <dom>
customization binds an XML Schema
component to DOM rather than to a strongly typed Java representation.
Specifically, JAXB bindings for mixed content and wildcard result in a
hybrid mixture of strongly typed Java instances with DOM nodes or
java.lang.String, representing text info. These mixed bindings might be
more easily processed solely as one form, namely as an XML fragment
represented as DOM. This customization also meets a Jakarta XML Web Services
databinding requirement from Disabling Databinding.
7.12.1. Usage
The syntax for the customization is the following:
<dom [ [type= "w3c" | otherDomRepresentations ] />
You can use the optional type attribute to specify the type of DOM. By default, it is W3C DOM.
7.12.2. Customizable Schema Elements
This customization can be attached to the following XML Schema components:
-
Element declaration (
<xs:element>
) -
Type definition (
<xs:complexType>
and<xs:simpleType>
) -
Wildcard (
<xs:any>
) -
Model groups (
<xs:choice>
,<xs:all>
,<xs:sequence>
) -
Model group definition (
<xs:group>
) -
Particle
For all of the above cases, the Java
representation of the DOM element is an instance of the Element class
for the specified DOM representation. For example, W3C DOM element is
bound to org.w3c.dom.Element
.
Special Case Handling of DOM customization on a:
-
type definition - it is semantically equivalent to placing the dom customization on each element declaration referencing that type definition.
-
global element declaration - it is semantically equivalent to placing the dom customization on each element declaration referencing, via
@ref
, the global element declaration. The dom customization on the global element declaration does not cause that element to be unmarshalled as DOM when it is the root element of an XML document nor when the element is part of a wildcard content JAXB property. -
mixed content - if an XML schema component is annotated with a
dom
customization and that XML schema component can contain character data information due to its parent complex type definition being defined with mixed content, character data information is handled as specified in Bind mixed content.
The dom customization allows one to disable databinding and process a part of a document using other technologies that require “raw” XML.
7.12.3. Examples
Wildcard Binding Example
A wildcard is mapped to a List of
org.w3c.dom.Element
. Each element that matches to the wildcard will
be turned into a DOM tree.
<xs:complexType name=”foo”>
<xs:sequence>
<xs:any maxOccurs="unbounded" processContents="lax">
<xs:annotation><xs:appinfo>
<jaxb:dom/>
</xs:appinfo></xs:annotation>
</xs:any>
</xs:sequence>
</xs:complexType>
import org.w3c.dom.Element;
public class Foo {
@XmlAnyElement(lax=”false”)
List<Element> getContent() {...}
}
Wildcard and Mixed Content Binding Example
If the complexType definition above is
defined to have mixed content, due to element [complexType] having
attribute @mixed="true"
, the JAXB binding is:
import org.w3c.dom.Element;
public class Foo {
/* Element content is represented org.w3c.dom.Element.
* Character data information is represented as instances of
* java.lang.String. */
@XmlMixed
@XmlAnyElement(lax=”false”)
List<Object> getContent() {...}
}
7.13. <inlineBinaryData>
Declaration
The <inlineBinaryData>
customization
provides declarative control over the optimization for binary data
described in Enhanced Binary Data Handling.
7.13.1. Usage
The syntax for the customization is the following:
<inlineBinaryData/>
This customization disables considering the binary data optimization for a schema component containing binary data.
This customization can be attached to the following XML Schema components:
-
Element declaration (
<xs:element>
) with binary data or -
Type definition (
<xs:complexType>
and<xs:simpleType>
) deriving from binary datatype
When a schema component that binds to a JAXB
property is customized with <inlineBinaryData>
, its schema-derived JAXB
property is annotated with @XmlInlineBinaryData
. When a type
definition is customized with <inlineBinaryData>
, its schema-derived
class is annotated with program annotation @XmlInlineBinaryData
.
7.14. <factoryMethod>
Declaration
The <factoryMethod>
customization provides
declarative control over an element or type factory method name
generated in a package’s ObjectFactory
class introduced in
Java Package. This customization is
useful to resolve name collisions between factory methods in the
schema-derived ObjectFactory
class.
7.14.1. Usage
The syntax for the customization is the following:
<factoryMethod name=”BaseForFactoryMethodName”/>
The customization value defined is:
-
name
- each character of name must be a valid part of a Java identifier as determined byjava.lang.Character.isJavaIdentifierPart()
.
The name of the factory method is generated by concatenating the following components:
-
The string constant
create
-
@name
’s value
7.14.1.1. Usage Constraints
The usage constraints on <factoryMethod>
are specified below. Any constraint violation must result in an invalid
customization as specified in Invalid Customizations.
The usage constraints are:
-
<factoryMethod>
is only allowed to annotate an element declaration or a type definition.
Note that this customization does not require a factory method to be generated, it simply provides a factory method name if a factory method is to be generated for the annotated element declaration or type definition. Section 6 and 7 specifies when a factory method is generated for an element declarations or type definitions.
7.15. Annotation Restrictions
[XSD PART 1] allows an annotation element to be specified for most elements but is ambiguous in some cases. The ambiguity and the way they are addressed are described here.
The source of ambiguity is related to the specification of an annotation element for a reference to a schema element using the “ref” attribute. This arises in three cases:
-
A local attribute references a global attribute declaration using the “ref” attribute.
-
A local element in a particle references a global element declaration using the “ref” attribute.
-
A model group in a particle references a model group definition using the “ref” attribute.
For example in the following schema fragment (for brevity, the declaration of the global element “Name” and “Address” has been omitted).
<xs:element name = "Customer">
<xs:complexType>
<xs:element ref = "Name"/>
<xs:element ref = "Address" />
</xs:complexType>
</xs:element>
XML Schema spec is ambiguous on whether an annotation element can be specified at the reference to the “Name” element.
The restrictions on annotation elements has been submitted as an issue to the W3C Schema Working Group along with JAXB technology requirements (which is that annotations should be allowed anywhere). Pending a resolution, the semantics of annotation elements where the XML spec is unclear are assumed as specified as follows.
This specification assumes that an annotation element can be specified in each of the three cases outlined above. Furthermore, an annotation element is assumed to be associated with the abstract schema component as follows:
-
The annotation element on an attribute ref is associated with {Attribute Use}
-
The annotation element on a model group ref or an element reference is associated with the {particle}.
8. Java Types To XML
8.1. Introduction
This chapter specifies the mapping from program elements to XML Schema. The mapping includes a default as well as a customized mapping.
8.2. Overview
This section is non normative and provides a high level view of Java to XML Schema mapping targeted towards both JAXB application developers and JAXB implementation vendors.
8.2.1. Mapping Scope
The mapping covers program elements commonly used in the composition of a data model for an application: package, field, property and types (classes and enum construct). Additionally, the mapping scope also covers mapping annotations used to annotate schema derived code.
In so far as possible, a program element is mapped to an equivalent XML Schema construct in an intuitive manner. Thus,
-
Package maps to a XML target namespace. A package provides a naming context for types. A XML target namespace provides a naming context for schema components such as elements, type definitions.
-
Type maps to a schema type. A value type is a data container for values; e.g. a value class contains values represented by it’s properties and fields. A schema type is a datatype, an instance of which (e.g. element) acts as a data container for values represented by schema components within a schema type’s content model (e.g. element, attributes, etc.). Thus a type maps naturally to a schema type. For e.g.,
-
class typically maps to a complex type definition
-
java primitive types and wrapper classes map to XML Schema simple type definition.
-
-
Field or property maps to an element or an attribute contained within the complex type to which a type is mapped.
-
Enum type maps to a simple schema type constrained by enumeration facets.
The input to the mapping process is one or more sets of packages or classes. A package or a class is mapped and recursively, fields, properties and types contained with it. The mapping is customizable.
8.2.2. Mapping Annotations
Mapping annotations The mapping of program elements to XML Schema construct can be customized using mapping annotations, program annotations based on JSR 175 program annotation facility. Mapping annotations are used for:
-
customizing the Java to XML schema mapping.
-
annotating schema derived code.
-
control over optimized binary data encoding.
The mapping annotations are described in the
jakarta.xml.bind.annotation
and jakarta.xml.bind.annotation.adapters
packages.
Retention Policy The retention policy of all mapping annotations is RetentionPolicy.RUNTIME. This policy allows introspection of mapping annotations at runtime. Introspection can be used by JAXB binding framework to marshal/unmarshal an object graph to XML representation or to customize the mapping of program elements to XML Schema constructs. This policy also allows a JAXB vendor implementation to generate a schema from a program element’s compiled form rather than its source.
8.2.3. XML Name Derivation
Mapped program element is a program element
that has been mapped to an XML Schema construct. It is possible to use
@XmlTransient
annotation type to prevent the mapping of a program
element.
XML Names An XML name may be needed for the
schema components for a mapped program element, for e.g. element name.
XML names are usually derived from a program element name, for e.g.
property, field, class name etc.But they can be customized using mapping
annotation. When an XML name is derived from a property name, bean de
capitalization rules are used. If a Java Identifier is not a legal XML
name, then a legal XML name can be assigned using an annotation element
(e.g. @XmlType(name="foo")
).
8.2.4. Fields and Properties
XML global element Fields and properties
typically map to local elements within a complex type for a class. But a
well formed XML document begins with a root element (a global element in
the corresponding schema). The @XmlRootElement
annotation can be used
to associate a global element with a class or an enum type.
Null Value and Nillable Element A null value for a type mapped to an XML Schema element in two ways: absence of an element or an nillable element. The mapping annotation for an element allows either mapping.
8.2.5. Type Mapping
Legacy applications One of the primary use cases for Java language to XML Schema mapping is to allow an existing application to be exported as a web service. In many cases, the existing applications are legacy applications consisting of classes that follow different class designs. The annotations and default mapping are designed to enable such classes to be mapped to schema with minimal changes to existing code. See Default Mapping for default mapping.
Class A class usually maps to a complex type.
However, using @XmlValue
annotation, a class can also be mapped to a
simple type (to hold a simple value) or a complexType with simpleContent
(to hold a simple value and attributes). The @XmlType
annotation can
be used to customize the mapping of a class. For example, it can be used
to map a class to an anonymous type or to control the ordering of
properties and/or fields. Properties and fields are unordered; but they
can be mapped to a content model that is ordered (e.g. xs:sequence) or
unordered content model (xs:all).
Class Designs A class with a public or
protected no-arg constructor can be mapped. If a class has a
static zero-arg factory method, then the factory method can be specified using
the annotation element @XmlType.factoryMethod()
and @XmlType.factoryClass()
.
Ordering of Properties/fields The ordering of
properties and fields can be customized in one of two ways: at the
package level using @XmlAccessorOrder
or using @XmlType.propOrder()
at
the class level.
Class Hierarchy Mapping Class hierarchy
typically maps to a type derivation hierarchy. The @XmlType
and
@XmlValue
annotations together provide support mapping class hierarchy
to schema type hierarchy where XML Schema complex type derives by
extension from either another complex type or a simple type.
Supported Collection Types Typed collections
and untyped collections are mapped. Mapped collection types are: arrays,
indexed properties and parametric types. Mapped untyped collection are:
java.util.List
, java.util.Set
and java.util.HashMap
. Of these,
java.util.HashMap
does not map naturally to a XML Schema construct.
For example, HashMap
can have different XML serialized forms which
differ in trade-offs made between memory and speed or specificity and
generality. The XML serialization form can be customized using
@XmlJavaTypeAdapter
(Adapter).
Collection serialized forms A collection type can be mapped to a XML Schema complex type and collection item is mapped to local element within it.
Alternately, a parameterized collection
(e.g. List<Integer>
) can be mapped to a simple schema type that derives
by list.
When a collection type is mapped to a XML Schema complex type, the mapping is designed to support two forms of serialization shown below.
//Example: code fragment
int[] names;
<!--XML Serialization Form 1 (Unwrapped collection)
Element name is derived from property or field name-->
<names> ... </names>
<names> ... </names>
...
<!--XML Serialization Form 2 (Wrapped collection)
Element name of wrapper is derived from property or field name
Element name of each item in collection is also derived from
property name-->
<names>
<names> value-of-item </names>
<names> value-of-item </names>
....
</names>
The two serialized XML forms allow a null
collection to be represented either by absence or presence of an element
with a nillable attribute. The @XmlElementWrapper
annotation on the
property or field is used to customize the schema corresponding to the
above XML serialization forms.
A parameterized collection (e.g.
List<Integer>)
can also be mapped to simple schema that derives by list
using @XmlList
annotation. For e.g. the serialized XML form is: "1 2 3".
8.2.6. Adapter
A type may not map naturally to a XML representation (see Supported Collection Types above). As another example, a single instance of a type may have different on wire XML serialization forms.
Adapter approach defines a portable customization mechanism for applications exemplified above. The mechanism provides a way to adapt a bound type, a Java type used to process XML content, to value type, mapped to an XML representation or vice versa. It is the value type that is used for marshalling and unmarshalling. Use of this approach involves two steps:
-
provide an adapter class that extends the abstract class
@jakarta.xml.bind.annotation.adapters.XmlAdapter
that defines two methodsunmarshal()
andmarshal()
. The methods are invoked by JAXB vendor implementation during unmarshalling and marshaling respectively to adapt between bound and value types. -
specify the adapter class using the
@XmlJavaTypeAdapter
annotation.
8.2.7. Referential Integrity
Preserving referential integrity of an object graph across XML serialization followed by a XML de serialization, requires an object reference to be marshalled by reference or containment appropriately. Possible strategies include:
-
marshal all references to a given object by reference.
-
marshal the first reference to an object by containment and subsequent references to the same object by reference.
Depending on the strategy, the schema to which program element is mapped also varies accordingly.
Two annotations @XmlID
and @XmlIDREF
provide the mechanism which can be used together to map program element
by reference or containment. This places the burden of preserving
referential integrity on a developer. On the other hand, the ability to
customize the mapping is useful since it can result in mapping of
program elements to a schema that defines a document structure more
meaningfully to an application than a default derived schema.
8.2.8. Property/Field Name Collision
A XML name collision can arise when the property name obtained by bean de capitalization and the name of a field map to a same schema component. For example
public int item;
public int getItem();
public void setItem(int val);
The name collision occurs because the property
name, bean de capitalization, and the name of the public field are both
the same i.e. item
. In the case, where the property and the public
field refer to the same field, the @XmlTransient
can be used to
resolve the name collision by preventing the mapping of either the
public field or the property.
8.3. Naming Conventions
Any source and schema fragments and examples shown in this chapter are meant to be illustrative rather than normative.
-
@XmlAttribute
denotes both a program annotation type as well a specific use of annotation type. -
The prefix
xs:
is used to refer to schema components in W3C XML Schema namespace. -
The prefix
ref:
is used to refer to schema components in the namespace"http://ws-i.org/profiles/basic/1.1/xsd"
Design Note
The mapping of program elements to schema components is specified using the abstract schema component model in XML Schema Part 1. The use of abstract schema components allows precise specification of the mapping and is targeted towards JAXB implementation vendors. In contrast, jakarta.xml.bind.annotation Javadoc is targeted towards the JAXB application developer. Hence it is the Javadoc that contains code and schema fragment samples. Default mapping is specified in terms of customizations. First the mapping of program element to a schema component with the binding annotation is specified. Then the default mapping for a program element is specified by defining a default binding annotation. In the absence of any binding annotation, the default binding annotation is considered to annotate the program element. For ease of reading, a synopsis of each program annotation is included inline in this chapter. Details can be found in the Javadoc published separately from this document. |
8.4. Constraint Violations
For the purpose of mapping and constraint checking, if a program element is not annotated explicitly, and there is a default mapping annotation defined for that element, it must be applied first before performing any constraint checks or mapping. This is assumed in the normative mapping tables shown below.
The mapping of program elements to XML Schema
constructs is subject to mapping constraints, specified elsewhere in
this chapter. The mapping constraints must be enforced by the
jakarta.xml.bind.annotation.JAXBContext.newInstance(..)
method. Any
cycles resulting from a combination of annotations or default mapping
must be detected in
jakarta.xml.bind.annotation.JAXBContext.newInstance(..)
method and also
constitutes a constraint violation. A jakarta.xml.bind.JAXBException
or
(its subclass, which can be provider specific) must be thrown upon a
constraint violation.
A JAXB Provider must support the schema
generation at runtime. See
jakarta.xml.bind.JAXBContext.generateSchema(..)
for more information.
8.5. Type Mapping
This section specifies the mapping of Java types to XML Schema.
8.5.1. Java Primitive types
The default mapping of Java types (and their wrapper classes) specified in table Mapping: Java Primitive types to Schema Types must be supported.
Java Primitive Type | XML data type |
---|---|
boolean |
xs:boolean |
byte |
xs:byte |
short |
xs:short |
int |
xs:int |
long |
xs:long |
float |
xs:float |
double |
xs:double |
8.5.2. Java Standard Classes
The default mapping of Java classes specified in Mapping of Standard Java classes must be supported.
Java Class | XML data type |
---|---|
java.lang.String |
xs:string |
java.math.BigInteger |
xs:integer |
java.math.BigDecimal |
xs:decimal |
java.util.Calendar |
xs:dateTim |
java.util.Date |
xs:dateTime |
javax.xml.namespace.QName |
xs:QName |
java.net.URI |
xs:string |
javax.xml.datatype.XMLGregorianCalendar |
xs:anySimpleType |
javax.xml.datatype.Duration |
xs:duration |
java.lang.Object |
xs:anyType |
java.awt.Image |
xs:base64Binary |
jakarta.activation.DataHandler |
xs:base64Binary |
javax.xml.transform.Source |
xs:base64Binary |
java.util.UUID |
xs:string |
Design Note
JAXP package javax.xml.datatype introduced the following classes for supporting XML schema types: Duration and XMLGregorianCalendar. XMLGregorianCalendar supports for 8 schema calendar types - xs:date, xs:time, xs:dateTime, 6 g* types, all of which derive from xs:anySimpleType. The particular schema type is computed based on values of member fields of XMLGregorianCalendar. Since the actual schema type is not known until runtime, by default, XMLGregorianCalendar can only be mapped to xs:anySimpleType and an instance of XMLGregorianCalendar could be marshaled using xsi:type to specify the appropriate schema calendar type computed at runtime. However, the mapping can be customized. |
A byte[] must map to xs:base64Binary by default.
8.5.3. Generics
8.5.3.1. Type Variable
The following grammar is from [JLS], Section 4.4, "Type Variables".
TypeParameter:
TypeVariable TypeBoundopt
TypeBound:
extends ClassOrInterfaceType AdditionalBoundListopt
A type variable without a Typebound must be mapped to xs:anyType.
A type variable with a TypeBound must map to the schema type to which ClassOrInterfaceType is mapped; the mapping of ClassOrInterface is subject to the mapping constraints specified in other sections in this chapter.
// code fragment
public class Shape <T> {
public T xshape;
public Shape() {};
public Shape(T f) {
xshape = f;
}
}
<!-- XML Schema -->
<xs:complexType name="shape">
<xs:sequence>
<xs:element name="xshape" type="xs:anyType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
8.5.3.2. Type Arguments and Wildcards
The following grammar is from [JLS], Section 4.5.1, "Type Arguments and Wildcards".
TypeArguments: <ActualTypeArgumentList> ActualTypeArgumentList: ActualTypeArgument ActualTypeArgumentList, ActualTypeArgument ActualTypeArgument: ReferenceType Wildcard Wildcard: ?WildcardBounds WildcardBounds: extends ReferenceType super ReferenceType
A wildcard without a WildcardBounds must map to schema type xs:anyType.
A wildcard with a WildcardBounds whose super type is ReferenceType must map to schema type xs:anyType.
A wildcard with a WildcardBounds that extends a ReferenceType must map to the schema type to which the ReferenceType is mapped; this mapping is subject to the mapping constraints specified in other sections in this chapter and is determined by the annotations as specified in the mapping tables in the chapter. For example:
/**
* EXAMPLE : WildcarType Mapping
*/
// Code fragment
public class Shape {...}
public class Rectangle extends Shape {...}
public class Circle extends Shape {...}
public class Foo {
public java.util.List<? extends Shape> shapes;
}
<!-- XML Schema fragment -->
<xs:complexType name="shape">
...
</xs:complexType>
<xs:complexType name="circle">
<xs:complexContent>
<xs:extension base="shape">
...
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="rectangle">
<xs:complexContent>
<xs:extension base="shape">
...
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="foo">
<xs:sequence>
<xs:element name="shapes" type="shape" nillable="true"
maxOccurs="unbounded" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
8.5.4. Collections
The following collection must be supported:
-
java.util.Map
and its subtypes (e.g. java.util.HashMap) -
java.util.Collection
and it’s subtypes (e.g. java.util.List)
The mapping of collection depends upon the
annotations on the program elements and is specified in the mapping
tables. This specification uses a collection type to be one of
java.util.Collection
(or a subtype derived from it), an array or an
JavaBean index property.
8.6. Java Package
@XmlSchema
is used in the mapping of package to an XML target namespace.
8.6.1. @XmlSchema
8.6.1.1. Synopsis
public enum XmlNsForm {UNQUALIFIED, QUALIFIED, UNSET}
@Retention(RUNTIME) @Target({})
public @interface XmlNs {...}
@Retention(RUNTIME) @Target({PACKAGE})
public @interface XmlSchema {
XmlNs[] xmlns() default {};
String namespace() default "";
String location() default "";
XmlNsForm elementFormDefault() default XmlNsForm.UNSET;
XmlNsForm attributeFormDefault() default XmlNsForm.UNSET;
}
8.6.1.2. Mapping
If location()
is "", a package annotated
with @XmlSchema
must be mapped as specified in Table 8-3 Mapping: Package to XML target namespace.
Otherwise a package will not produce any schema document.
Design Note
XML Schema Part 1 does not contain an abstract component definition for a schema. Neither is there a mapping of attribute information items (e.g. elementFormDefault) of the <schema> to properties of an abstract schema component. So the mapping below maps to attribute information items on the <schema> element. "absent" in the tables is used to mean absence of the attribute information item in the schema. |
Design Note
When |
|
if |
|
if the value of |
|
if the value of |
|
if |
8.6.2. @XmlAccessorType
This annotation allows control over default serialization of fields and properties.
8.6.2.1. Synopsis
@Inherited @Retention(RUNTIME) @Target({PACKAGE, TYPE})
public @interface XmlAccessorType {
XmlAccessType value() default XmlAccessType.PUBLIC_MEMBER;
}
public enum XmlAccessType { NONE, PROPERTY, FIELD, PUBLIC_MEMBER }
8.6.2.2. Mapping
The following mapping constraints must be enforced:
-
This annotation can be used only with the following other annotations:
@XmlType
,@XmlRootElement
,@XmlAccessorOrder
,@XmlSchema
,@XmlSchemaType
,@XmlSchemaTypes
,@XmlJavaTypeAdapters
. It can also be used with the following annotations at the package level:@XmlJavaTypeAdapter
.
See Default Mapping.
8.6.3. @XmlAccessorOrder
This annotation allows control over the default ordering of properties and fields that are mapped to XML elements. Properties and fields mapped to XML attributes are not impacted by this annotation since XML attributes are unordered.
8.6.3.1. Synopsis
@Inhertited @Retention(RUNTIME)
@Target({PACKAGE, TYPE})
public @interface XmlAccessorOrder {
XmlAccessOrder value() default XmlAccessOrder.UNDEFINED;
}
public enum XmlAccessOrder { UNDEFINED, ALPHABETICAL }
8.6.3.2. Mapping
The following mapping constraints must be enforced:
-
This annotation can be used only with the following other annotations:
@XmlType
,@XmlRootElement
,@XmlAccessorType
,@XmlSchema
,@XmlSchemaType
,@XmlSchemaTypes
,@XmlJavaTypeAdapters
. It can also be used with the following annotations at the package level:@XmlJavaTypeAdapter
. -
If the value of
@XmlAccessorOrder.value()
isXmlAccessOrder.ALHPHABETICAL
, then the default ordering of fields/properties is lexicographic order as determined byjava.lang.String.CompareTo(String anotherString)
. -
If the
@XmlAccessorOrder.value()
isXmlAccessOrder.UNDEFINED
, then the default ordering of fields/properties is unspecified.
8.6.4. @XmlSchemaType
This annotation allows a customized mapping to
a XML Schema built in type. This is useful where a Java type can map to
more than one schema built in types. An example is
XMLGregorianCalendar
which can represent one of the eight schema
built-in types.
8.6.4.1. Synopsis
@Retention(RUNTIME)
@Target({FIELD, METHOD, PACKAGE})
public @interface XmlSchemaType {
String name();
String namespace() default "http://www.w3.org/2001/XMLSchema";
Class type() default DEFAULT.class;
static final class DEFAULT {}
}
8.6.4.2. Mapping
The following mapping constraints must be enforced:
-
name()
must be an atomic simple type schema type (or a type that derives from it) to which the type of the property or field can be mapped from XML Schema → Java as specified in Section 6.2.2, "Atomic Datatype".Example
// @XmlSchemaType can specify any one of the eight calendar types // that map to XMLGregorianCalendar. @XmlSchemaType(name="date") XMLGregorianCalendar foo;
-
If the annotation is used as a package level annotation or within
@XmlSchemaTypes
, value of@XmlSchemaType.type()
must be specified and must be the Java type that is being customized. -
If the annotation is used on a field or a method, then value of
type()
must beDEFAULT.class
. -
This annotation can only be used with the following other annotations:
@XmlElement
,@XmlAttribute
,@XmlJavaTypeAdapter
,@XmlJavaTypeAdapters
.
package:
When this annotation is used at the package
level, the mapping applies to references to @XmlSchemaType.type()
as
specified below. For clarity, the following code example is used along
with normative text.
// Example: change the default mapping at package level
package foo;
@jakarta.xml.bind.annotation.XmlSchemaType
(name="date",
type=javax.xml.datatype.XMLGregorianCalendar.class)
A @XmlSchemaType
that is specified as a
package level annotation must apply at the point of reference as
follows:
-
a property/field within a class in package (e.g
exmple.po
) whose reference type is@XmlSchemaType.type()
. For e.g.// XMLGregorianCalendar will be mapped to XML Schema type "date" XMLGregorianCalendar cal;
-
a property/field within a class in package (e.g
exmple.po
), where@XmlSchemaType.type()
is used as a parametric type. For e.g.// Example: Following code maps to a repeating element with // XML Schema type of "date". List<XMLGregorianCalendar> bar;
property/field:
A @XmlSchemaType
specified on the
property/field maps references to @XmlSchemaType.type()
as follows:
-
property/field is a single valued.
// Maps XMLGregorianCalendar to XML Schema type "date"" @XmlSchemaType(name="date") public XMLGregorianCalendar cal;
-
a property/field where
@XmlSchemaType.type()
is used as a parametric type. For e.g.// Example: Following code maps to a repeating element with // XML Schema type of "date". @XmlSchemaType(name="date") List<XMLGregorianCalendar> bar;
8.6.5. @XmlSchemaTypes
This annotation is a container annotation for
defining multiple @XmlSchemaType
annotations at the package level.
8.6.5.1. Synopsis
@Retention(RUNTIME) @Target({PACKAGE})
public @interface XmlSchemaTypes {
// Collection of @{@link XmlSchemaType} annotations
XmlSchemaType[] value();
}
8.6.5.2. Mapping
Each @XmlSchemaType
annotation in
@XmlSchemaTypes.value()
must be mapped as specified in @XmlSchemaType.
8.7. Java class
8.7.1. @XmlType
@XmlType
is used to map a Java class to a
schema type. The schema type is computed from its annotation element
values.
8.7.1.1. Synopsis
@Retention(RUNTIME) @Target({TYPE})
public @interface XmlType {
String name() default "##default";
String[] propOrder() default {""};
String namespace() default "##default";
Class factoryClass() default DEFAULT.class;
static final class DEFAULT {};
String factoryMethod() default "";
}
8.7.1.2. Mapping
The following mapping constraints must be enforced:
-
a class must be either be a top level class or a nested static class.
-
a class must have a public or protected no-arg constructor or a factory method identified by {
factoryClass()
,factoryMethod()
} unless it is adapted using@XmlJavaTypeAdapter
. -
If
factoryClass()
is other thanDEFAULT.class
, thenfactoryMethod()
must be specified (i.e. the default value "" cannot be used.) -
If
factoryClass()
isDEFAULT.class
andfactoryMethod()
is not "", thenfactoryMethod()
be a method in this class. -
if
@XmlType.propOrder
is not {} or {""}, then the set must include all of the properties and fields mapped to particles as specified in: -
@XmlType.propOrder
must not include a field or property annotated with@XmlTransient
. -
if the class, subClass, derives from another XML-bound class, baseClass directly or indirectly (other than
java.lang.Object
), then the subClass must not contain a mapped property or field annotated with@XmlValue
annotation. -
If a class contains a mapped property or field annotated with
@XmlValue
annotation, then all other mapped fields or properties in the class must be mapped to an XML attribute. -
This annotation can be used with the following annotations:
@XmlRootElement
,@XmlAccessorOrder
,@XmlAccessorType
. -
Even though the syntax allows it,
@XmlType
is disallowed on an interface.
A class annotated with @XmlType
, must be
mapped as specified below:
-
class must be mapped as specified in Table 8-6 Mapping: Class to Simple Type Definition if the class contains only one mapped property or field that is annotated with
@XmlValue
as specified in @XmlValue. -
otherwise, the class must be mapped as specified in Table 8-4 Mapping: Class to Complex Type Definition.
|
if |
||
|
if |
||
|
if the class contains a mapped property or
field annotated with
|
||
|
if |
||
|
if class modifier |
||
|
|
||
|
The set of properties or fields mapped to attributes as specified in @XmlAttribute. |
||
|
Attribute wildcard as specified in XmlAnyAttribute. |
||
|
|
||
|
|
||
|
|
|
if |
|
Set of properties or fields mapped to
particles. See |
|
|
|
if |
|
|
if |
|
|
ur-type definition, |
|
|
|
|
|
derived |
|
|
|
|
|
Must be mapped as shown below |
|
atomic |
if property or field type is one of:
|
|
list |
if the property or field type is one of the following collection types:
|
|
union |
Not mapped. |
|
|
|
8.7.2. @XmlRootElement
@XmlRooElement
can be used to associate a
global element with the schema type to which a class is mapped.
8.7.2.1. Synopsis
@Retention(RUNTIME) @Target({TYPE}
public @interface XmlRootElement {
String name() default "##default";
String namespace() default "##default";
}
8.7.2.2. Mapping
The following mapping constraints must be enforced:
-
The only other annotations allowed with this annotation are:
@XmlType
,@XmlEnum
,@XmlAccessorType
,@XmlAcessorOrder
.
A class annotated with @XmlRootElement
annotation, must be mapped as specified in Table 8-7 Mapping: Class to Element Declaration.
|
if |
||
|
if |
||
|
schema type to which the class is mapped as specified in @XmlType. |
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
8.7.3. @XmlTransient
@XmlTransient
is used to prevent the mapping of a class.
8.7.3.2. Mapping
The class must not be mapped. Any reference to
this class from the other XML-bound classes will treated as if they are
refering to the nearest XML-bound ancestor of this class (which could be
java.lang.Object
, which guarantees that there always exists such a
class.)
For the effect that this annotation causes on derived classes, see Table 8-4 Mapping: Class to Complex Type Definition.
Note that a class with`@XmlTransient` may still have properties and fields with JAXB annotations. Those are mapped to XML when a derived class is mapped to XML. See Property And Field for more details.
The following mapping constraints must be enforced:
-
@XmlTransient
is mutually exclusive with all other mapping annotations.
8.8. Enum Type
8.8.1. @XmlEnum
8.8.1.1. Synopsis
@Retention(RUNTIME) @Target({TYPE})
public @interface XmlEnum {
// Java type that is mapped to a XML simple type
Class <?> value() default String.class;
}
8.8.1.2. Mapping
The following mapping constraints must be enforced:
-
@XmlEnum.value()
must be mapped to a XML schema simple type.
|
schema type to which |
||
|
The value depends upon the schema type to which the
|
8.8.2. @XmlEnumValue
8.8.3. @XmlType
8.8.3.1. Synopsis
@Retention(RUNTIME) @Target({TYPE})
public @interface XmlType {
String name() default "##default";
String namespace() default "##default";
String[] propOrder() default {""};
Class factoryClass() default DEFAULT.class;
static final class DEFAULT {};
String factoryMethod() default "";
}
8.8.3.2. Mapping
The following mapping constraints must be enforced:
-
factoryMethod()
,factoryClass()
and@XmlType.propOrder
must be ignored. -
This annotation can be used only with the following other annotations:
@XmlRootElement
,@XmlAccessorOrder
,@XmlAccessorType
. However,@XmlAccessorOrder
and@XmlAccessorType
must be ignored; they are not meaningful when used to annotate an enum type.
|
if |
|
if |
|
Mapped as specified in Table 8-8 Mapping: Enum type to Base Type Definition. |
|
Mapped as specified in Table 8-8 Mapping: Enum type to Base Type Definition. |
|
|
|
the set constructed by mapping each enum constant to an enumeration schema component as specified in Table 8-9 Mapping: Enum constant to Enumeration Schema Component. |
|
|
|
|
8.8.4. @XmlRootElement
@XmlRootElement
can be used to associate a
global element with the schema type to which the enum type is mapped.
8.8.4.1. Mapping
The following mapping constraints must be enforced:
-
The only other annotations allowed with this annotation are:
@XmlType
,@XmlEnum
,@XmlAccessorType
,@XmlAcessorOrder
.
Note that@XmlAccessorType
and@XmlAccessorOrder
while allowed will be ignored by the constraint in Mapping.
The mapping must be performed as specified in Table 8-11 Mapping: Enum type to Element Declaration.
|
if otherwise |
||
|
if otherwise |
||
|
schema type to which the class is mapped as specified in @XmlType. |
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
8.9. Property And Field
The following must be mapped (subject to the mapping constraints listed below):
-
read/write property as identified by
java.beans.Introspector.getBeanInfo
with its nearest XML-bound superclass as the stopClass. -
non static, non transient field of all the ancestors up to the stopClass (but excluding the stopClass itself); if annotated with
@XmlAttribute
, then static final field must be mapped (informally this maps to a fixed attribute but this is formally specified in the mapping tables below).
A mapped property is a property found as above and mapped either by default or using a JAXB annotation.
A mapped field is a field found as above and mapped either by default or using a JAXB annotation.
A property or field that has been annotated
with @XmlTransient
is not mapped.
The following mapping constraints must be enforced.
-
For a property, a given annotation can be applied to either read or write property but not both.
-
A property name must be different from any other property name in any of the super classes of the class being mapped.
-
A mapped field name or the de capitalized name of a mapped property must be unique within a class. For e.g.
// Example 1: // Both the field "x" and property getX/setX are mapped by // default. However, the decapitalized name property getX/setX // is also "x" which collides with the field name "x". public class Foo { public int x; public int getX {...}; public void setX {...}; }
8.9.1. @XmlElement
8.9.1.1. Synopsis
@Retention(RUNTIME) @Target({FIELD, METHOD}
public @interface XmlElement {
String name() default "##default"; // name for XML element
boolean nillable() default false;
boolean required() default false;
String namespace() default "##default";
Class type() default DEFAULT.class;
String defaultValue() default "\u0000";
static final class DEFAULT {}
}
8.9.1.2. Mapping
The following mapping constraints must be enforced:
-
The only additional mapping annotations allowed with
@XmlElement
are:@XmlID
,@XmlIDREF
,@XmlList
,@XmlSchemaType
,@XmlValue
,@XmlAttachmentRef
,@XmlMimeType
,@XmlInlineBinaryData
,@XmlJavaTypeAdapter
and@XmElementWrapper
.@XmlElement
can also be used within@XmlElements
. -
If the property or field type is a parametric collection type, then
@XmlElement.type()
must beDEFAULT.class
orcollectionitem.class
(since the type of the collection is already known).
A field or property annotated must be mapped as follows:
-
If
@XmlElement.namespace()
is not"##default"
and different from the{target namespace}
of the enclosing class, then it must be mapped as specified in Table 8-12 Mapping: Property/field to Particle - ref attribute. -
If property is single valued, and it’s type is annotated with
@XmlRootElement
and@XmlType.name() = ""
, then the property must be mapped as specified in Table 8-12 Mapping: Property/field to Particle - ref attribute.Design NoteThis mapping is designed to eliminate an infinite recursion. For example:
// Code fragment @XmlRootElement @XmlType(name="") class Foo { Foo foo; }
In the absence of the above mapping, the above code would map to:
<schema> <element name="foo"> <complexType> <sequence> <element name="foo" minOccurs="0"> <complexType> ... infinite recursion ...
With the above mapping, the code fragment would instead map to:
<schema> <element name="foo"> <complexType> <sequence> <element ref="foo" minOccurs="0">
-
otherwise, it must be mapped as Table 8-13 Mapping: Property/field to Particle - no ref attribute.
Design Note
A local element corresponds to two abstract schema components - a particle and an element declaration. This is reflected in the mapping shown below. |
|
if if the property type is a primitive type or a
multi dimensional array with a primitive type then otherwise |
||
|
if the type of the property/field is not a
collection type, then otherwise |
||
|
element declaration as specified in Table 8-14 Mapping: Property/field to Element declaration
with the following overrides for the abstract schema component properties:
|
|
if otherwise if the property type is a primitive
type or a multi dimensional array with a primitive type then otherwise |
|
if the type of the property/field is not a
collection type, then otherwise |
|
must be mapped as specified in Table 8-14 Mapping: Property/field to Element declaration. |
|
if otherwise |
|
if
otherwise, |
|
Note: The order of type inference below is significant. if otherwise if annotated with otherwise if annotated with otherwise if annotated with otherwise if annotated with otherwise if the property or field is a collection type, then the schema type derived by mapping the collection item type. otherwise the schema type to which the type of the property is mapped. |
|
complex type to which the property’s or the field’s containing class is mapped as specified in @XmlSchema. |
|
if otherwise default value with the value
|
|
|
|
|
|
|
|
{ |
|
{ |
|
|
|
|
8.9.2. @XmlElements
8.9.2.1. Synopsis
@Retention(RUNTIME) @Target({FIELD,METHOD})
public @interface XmlElements {
XmlElement[] value(); // collection of @XmlElement annotations
}
8.9.2.2. Mapping
The following mapping constraints must be enforced:
-
If the property or field type is a parameterized collection type, then the size of the
@XmlElements.value()
must be1
. -
This annotation can be used only with the following annotations:
@XmlIDREF
,@XmlElementWrapper
,@XmlJavaTypeAdapter
. -
If
@XmlIDREF
is specified, then each@XmlElement.type()
must contain a JavaBean property/field annotated with@XmlID
.
The property or field must be mapped as follows:
-
If the size of
@XmlElements.value()
is1
, then the property must be mapped as specified in @XmlElement. -
otherwise it must be mapped as specified in Table 8-15 Mapping: List of types to choice particle.
|
|
|
|
|
If |
|
|
|
set obtained by mapping each |
|
|
8.9.3. @XmlElementRef
8.9.3.1. Synopsis
@Retention(RUNTIME) @Target({FIELD, METHOD}
public @interface XmlElementRef {
String name() default "##default"; // name for XML element
String namespace() default "##default";
Class type() default DEFAULT.class;
static final class DEFAULT {}
}
8.9.3.2. Mapping
The following mapping constraints must be enforced:
-
The only other additional JAXB mapping annotations allowed with
@XmlElementRef
are:@XmlElementWrapper
and@XmlJavaTypeAdapter
. -
If the collection item type or property type (for single valued property) is
jakarta.xml.bind.JAXBElement
, then {@XmlElementRef.name()
,@XmlElementRef.namespace()
} must point an element factory method with an@XmlElementDecl
annotation in a class annotated with@XmlRegistry
(usuallyObjectFactory
class generated by the schema compiler):-
@XmlElementDecl.name()
must equal@XmlElementRef.name()
-
@XmlElementDecl.namespace()
must equal@XmlElementRef.namespace()
.
-
-
If the collection item type (for collection property) or property type (for single valued property) is not
jakarta.xml.bind.JAXBElement
, then the type referenced by the property or field must be annotated with@XmlRootElement
.
A field or property annotated with the
@XmlElementRef
annotation must be mapped as follows:
-
if the type of the property or field is single valued property, then it must be mapped as specified in Table 8-17 Mapping: Property/field (property type single valued) to Particle with ref attribute
-
otherwise (the type of the property or field is a parametric type), then it must be mapped as specified in Table 8-19 Mapping: Property/Field (parametric type) to choice particle.
|
if otherwise |
|
|
|
must be mapped as specified in Table 8-18 Mapping: Property/field to Element declaration with ref attribute. |
|
if otherwise if |
|
if otherwise if |
|
|
|
|
|
|
|
If |
|
|
|
set obtained by visiting parametric type and each of its derived types and if annotated with @XmlRootElement, then mapping the @XmlRootElement as specified in as specified in Table 8-18 Mapping: Property/field to Element declaration with ref attribute. |
|
|
8.9.4. @XmlElementRefs
8.9.4.1. Synopsis
@Retention(RUNTIME) @Target({FIELD,METHOD})
public @interface XmlElementRefs {
XmlElementRef[] value();
}
8.9.4.2. Mapping
The following mapping constraints must be enforced:
-
The only other additional JAXB mapping annotations allowed with
@XmlElementRefs
are:@XmlElementWrapper
and@XmlJavaTypeAdapter
.
The property or field must be mapped as specified in Table 8-21 Mapping: List of element instances to choice particle.
|
|
|
|
|
If the |
|
|
|
set obtained by mapping
|
|
|
8.9.5. @XmlElementWrapper
8.9.5.1. Synopsis
@Retention(RUNTIME) @Target({FIELD, METHOD}
public @interface XmlElementWrapper {
String name() default "##default" ; // name for XML element
String namespace() default "##default";
boolean nillable() default false;
boolean required() default false;
}
8.9.5.2. Mapping
The following mapping constraints must be enforced:
-
The only additional mapping annotations allowed with
@XmlElementWrapper
are:@XmlElement
,@XmlElements
,@XmlElementRef
,@XmlElementRefs
,@XmlJavaTypeAdapter
. -
The property or the field must be a collection property.
The property or field must be mapped as follows:
-
If
@XmlElementWrapper.namespace()
is not"##default"
and different from the{target namespace}
of the enclosing class, then it must be mapped as specified as specified in Table 8-25 Mapping: Property/field Element Wrapper with ref attribute. -
otherwise, it must be mapped as Table 8-23 Mapping: Property/field to Particle for Element Wrapper.
|
if otherwise |
|
|
|
must be mapped as specified in Table 8-24 Mapping: Property/field to Element Declaration for Element Wrapper. |
|
if otherwise |
|
if
otherwise |
|
if property/field is annotated with
otherwise if property/field is annotated with
|
|
complex type to which the property’s or the field’s containing class is mapped. |
|
|
|
|
|
|
|
|
|
{ |
|
{ |
|
|
|
|
|
|
||
|
|
||
|
element declaration whose
|
8.9.6. @XmlAnyElement
8.9.6.1. Synopsis
@Retention(RUNTIME) @Target({FIELD, METHOD})
public @interface XmlAnyElement {
boolean lax() default false;
Class<? extends DomHandler> value() default W3CDomHandler.class;
}
8.9.6.2. Mapping
The following mapping constraints must be enforced:
-
The only other JAXB annotations allowed with
@XmlAnyElement
are:@XmlElementRefs
. -
There must be only one property or field that is annotated with
@XmlAnyElement
. -
If a baseType has a property annotated with
@XmlAnyElement
, then no other sub type in the inheritance hierarchy rooted at baseType can contain a property annotated with@XmlAnyElement
.
The property or field must be mapped as specified in Table 8-26 Mapping: Wildcard schema component for wildcard (xs:any).
|
|
|
|
|
|
8.9.7. @XmlAttribute
@XmlAttribute
is used to map a property or a field to an XML attribute.
8.9.7.1. Synopsis
@Retention(RUNTIME) @Target({FIELD, METHOD})
public @interface XmlAttribute {
String name() default "##default";
boolean required() default false;
String namespace() default "##default";
}
8.9.7.2. Mapping
The following mapping constraints must be enforced:
-
If the type of the field or the property is a collection type, then the collection item type must be mapped to schema simple type. Examples:
@XmlAttribute List<Integer> foo; // legal @XmlAttribute List<Bar> foo; // illegal if Bar does not map to a // schema simple type
-
If the type of the field or the property is a non collection type, then the type of the property or field must map to a simple schema type. Examples:
@XmlAttribute int foo; // legal @XmlAttribute Foo foo; // illegal if Foo does not map to a schema // simple type
-
The only additional mapping annotations allowed with
@XmlAttribute
are:@XmlID
,@XmlIDREF
,@XmlList
,@XmlSchemaType
,@XmlValue
,@XmlAttachmentRef
,@XmlMimeType
,@XmlInlineBinaryData
,@XmlJavaTypeAdapter
.
Design Note
The mapping below supports mapping to either a local attribute or a reference
to a global attribute that already exists. The latter is useful for mapping to
attributes in foreign namespaces for e.g. <xs:attribute ref="xml:lang"/>.
Note that the attribtue is never created in the namespace, |
The property or field must be mapped as follows:
-
If
@XmlAttribute.namespace()
is not"##default"
and differs from the{target namespace}
of the schema type to which the type containing the property or field is mapped, then the property or field must be mapped as specified in Table 8-27 Mapping: Property/field to Attribute Use (with ref attribute). -
otherwise, it must be mapped as specified in Table 8-28 Mapping: Property/field to Attribute Use (no ref attribute).
|
|
|
attribute declaration whose
|
|
|
|
|
|
|
|
Mapped as specified in Table 8-29 Mapping: Property/field to Attribute Declaration |
|
if field has access modifiers public and
static then the otherwise |
|
if otherwise |
|
if otherwise |
|
if annotated with otherwise if annotated with otherwise if annotated with otherwise if the type of the property is a collection type, then the schema type derived by mapping the collection item type. otherwise the schema type to which the type of the property is mapped. |
|
complex type of the containing class |
|
if field has access modifiers static and final then otherwise |
|
|
8.9.8. XmlAnyAttribute
8.9.8.2. Mapping
The following mapping constraints must be enforced:
-
There must be only one property or field in a class that is annotated with
@XmlAnyAttribute
. -
The type of the property or the field must be
java.util.Map
. -
The only other annotations that can be used on the property or field with
@XmlAnyAttribute
are:@XmlJavaTypeAdapter
.
The property or field must be mapped as specified in Table 8-30 Mapping: Wildcard schema component for Attribute Wildcard.
|
|
|
|
|
|
8.9.9. @XmlTransient
@XmlTransient
is used to prevent the mapping of a property or a field.
8.9.10. @XmlValue
8.9.10.2. XmlValue Type Mapping
The following mapping constraints must be enforced:
-
At most one field or a property in a class can be annotated with
@XmlValue
. -
@XmlValue
can be used with the following annotations:-
@XmlList
- however this is redundant since@XmlList
maps a type to a schema simple type that derives by list just as@XmlValue
would. -
@XmlJavaTypeAdapter
-
-
If the type of the field or property is a collection type, then the collection item type must map to a simple schema type.
Examples:// Examples (not exhaustive): Legal usage of @XmlValue @XmlValue List<Integer> foo; // int maps to xs:int @XmlValue String[] foo; // String maps to xs:string @XmlValue List<Bar> foo; // only if Bar maps to a simple // schema type
-
If the type of the field or property is not a collection type, then the type of the property or field must map to a schema simple type.
-
The containing class must not extend another class (other than
java.lang.Obect
).
8.9.10.3. Mapping
-
If the type of the property or field is a collection type, then the type must be must be mapped as specified in Table 8-31 @XmlValue: Mapping to list simple type.
-
Otherwise, the schema type to which the type of the property or field is mapped.
|
|
|
|
|
ur-type definition, |
|
|
|
|
|
|
|
list |
|
if the field, property or parameter is a collection type
otherwise
|
|
|
8.9.11. @XmlID
8.9.11.2. Mapping
The following mapping constraints must be enforced:
-
at most one field or property in a class can be annotated with
@XmlID
. -
The type of the field or property must be
java.lang.String
. -
The only other program annotations allowed with
@XmlID
are:@XmlAttribute
and@XmlElement
.
The type of the annotated program element must
be mapped to xs:ID
.
8.9.12. @XmlIDREF
8.9.12.2. Mapping
The following mapping constraints must be enforced:
-
If the type of the field or property is a collection type, then the collection item type must contain a property or field annotated with
@XmlID
. -
If the field or property is not a collection type, then the type of the property or field must contain a property or field annotated with
@XmlID
.NoteIf the collection item type or the type of the property (for non collection type) is
java.lang.Object
, then the instance must contain a property/field annotated with@XmlID
attribute. -
The only additional mapping annotations allowed with
@XmlIDREF
are:@XmlElement
,@XmlAttribute
,@XmlList
, and@XmlElements
,@XmlJavaTypeAdapter
.
If the type of the field or property is a
collection type, then each collection item type must be mapped to
xs:IDREF
.
If the type of the field or property is single
valued, then the type of the property or field must be mapped to
xs:IDREF
.
8.9.13. @XmlList
This annotation maps a collection type to a list simple type.
8.9.13.1. Synopsis
@Retention(RUNTIME) @Target({FIELD, METHOD, PARAMETER})
public @interface XmlList {}
8.9.13.2. Mapping
The following mapping constraints must be enforced:
-
The type of the field, property or parameter must be a collection type.
-
The collection item type must map to a simple schema type that does not derive by list. For example:
// Examples: Legal usage of @XmlList @XmlList List<Integer> foo; // int maps to xs:int @XmlList String[] foo; // String maps to xs:string @XmlList List<Bar> foo; // only if Bar maps to a simple type // Example: Illegal usage of @XmlList public class Foo { // @XmlValue maps List to a XML Schema listsimple type @XmlValue List<Integer> a; } class Bar { // Use of @XmlList is illegal since Fooitself mapped // to a XML Schema list simple type; XMLSchema list simple // type can't derive from another XML Schemalist simple type @XmlList List<Foo> y; }
-
The only additional mapping annotations allowed with
@XmlList
are:@XmlElement
,@XmlAttribute
,@XmlValue
and@XmlIDREF
,@XmlJavaTypeAdapter
.
The type of the property or field must be mapped as specified in Table 8-32 @XmlList: Mapping to list simple type.
|
|
|
|
|
ur-type definition, |
|
|
|
|
|
|
|
list |
|
if annotated with otherwise the schema type to which the collection item type is mapped. |
|
|
8.9.15. @XmlMimeType
8.10. ObjectFactory Method
The annotations in this section are intended primarily for use by schema compiler in annotating element factory methods in the schema derived ObjectFactory class (Java Package). They are not expected to be used when mapping existing classes to schema.
8.10.1. @XmlElementDecl
8.10.1.1. Synopsis
@Retention(RUNTIME) @Target({METHOD})
public @interface XmlElementDecl {
Class scope() default GLOBAL.class;
// XML namespace of element
String namespace() default "##default";
String name(); // local name of element
//XML namespace name of a substitution group's head element.
String substitutionHeadNamespace() default "##default";
//XML local name of a substitution group's head element.
String substitutionHeadName() default "";
public final class GLOBAL {}
}
8.10.1.2. Mapping
The following mapping constraints must be enforced:
-
annotation can only be used on an element factory method (Java Package). The annotation creates a mapping between an XML schema element declaration and a element factory method that returns a
JAXBElement
instance representing the element declaration. Typically, the element factory method is generated (and annotated) from a schema into theObjectFactory
class in a Java package that represents the binding of the element declaration’s target namespace. Thus, while the annotation syntax allows@XmlElementDecl
to be used on any method, semantically its use is restricted to annotation of element factory method -
class containing the element factory method annotated with
@XmlElementDecl
must be annotated with@XmlRegistry
. -
element factory method must take one parameter assignable to
java.lang.Object
. -
two or more element factory methods annotated with
@XmlElementDecl
must not map to element declarations with identical{name}
{target namespace}
values. -
if type
Foo
has an element factory method and is also annotated with @XmlRootElement, then they must not map to element declarations with identical{name}
and{target namespace}
values.One example of where the above scenario occurs is when a developer attempts to add behavior/data to code generated from schema. For e.g. schema compiler generates an element instance factory method (e.g.
createFoo
) annotated with@XmlElementDec
. But the developer annotatesFoo
with@XmlRootElement
.
An element factory method must be mapped as specified in Table 8-34 Mapping: Element Factory method to Element Declaration.
|
|
|
if otherwise |
|
schema type to which the class is mapped as specified in @XmlType. |
|
otherwise the complex type definition to which the class containing the object factory method is mapped. |
|
|
|
|
|
|
|
element declaration derived from
|
|
|
|
|
|
|
|
|
8.11. Adapter
8.11.1. XmlAdapter
public abstract class XmlAdapter<ValueType,BoundType> {
// Do-nothing constructor for the derivedclasses.
protected XmlAdapter() {}
// Convert a value type to a bound type.
public abstract BoundType unmarshal(ValueType v);
// Convert a bound type to a value type.
public abstract ValueType marshal(BoundType v);
}
For an overview, see the section, Adapter.
For detailed information, see the javadocs for
jakarta.xml.bind.annotation.adapters.XmlAdapter
and
jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter
.
8.11.2. @XmlJavaTypeAdapter
8.11.2.1. Synopsis
@Retention(RUNTIME) @Target({PACKAGE,FIELD,METHOD,TYPE,PARAMETER})
public @interface XmlJavaTypeAdapter {
Class<? extends XmlAdapter> value();
Class type() default DEFAULT.class;
static final class DEFAULT {}
}
For an overview, see Adapter.
8.11.2.2. Scope
The scope of @XmlJavaTypeAdapter
must cover
the program elements as specified below:
package:
For clarity, the following code example is used along with normative text.
// Adapts Foo type to MyFoo type
FooAdapter extends XmlAdapter<MyFoo, Foo>
// FooAdapter is installed at the package level - example.po
@XmlJavaTypeAdapter(value=FooAdapter.class, type=Foo.class)
A @XmlJavaTypeAdapter
that extends
XmlAdapter<valueType, boundType>
and is specified as a package level
annotation must adapt boundType
at the point of reference as follows:
-
a property/field/parameter within a class in package (e.g
exmple.po)
whose reference type isboundType
. For e.g.// Foo will be adapted to MyFoo Foo foo;
-
a property/field/parameter within a class in package (e.g
exmple.po
), whereboundType
is used as a parametric type. For e.g.// List<Foo> will be adapted to List<MyFoo> Foo foo;
class, interface, enum type:
For clarity, the following code example is used along with normative text.
// Adapts Foo type to MyFoo type
FooAdapter extends XmlAdapter<MyFoo, Foo>
// FooAdapter is specified on class, interface or enum type.
@XmlJavaTypeAdapter(FooAdapter.class)
public class Foo {...}
A @XmlJavaTypeAdapter
that extends
XmlAdapter<valueType, boundType>
and is specified on the class,
interface or Enum type (i.e. on a program element that matches meta
annotation @Target={type}
) must adapt boundType
at the point of
reference as follows:
-
a property/field whose reference type is
boundType
. For e.g.// Foo will be adapted to MyFoo Foo foo;
-
a property/field where
boundType
is used as a parametric type. For e.g.// List<Foo> will be adapted to List<MyFoo> List<Foo> foo;
Note
A
|
property/field/parameter:
A @XmlJavaTypeAdapter
that extends
XmlAdapter<valueType, boundType>
and is specified on the
property/field or parameter must adapt boundType
as follows:
-
property/field is a single valued and its type is
boundType
:// Foo will be adapted to MyFoo @XmlJavaTypeAdapter(FooAdapter.class) Foo foo;
-
a property/field where
boundType
is used as a parametric type. For e.g.// List<Foo> will be adapted to List<MyFoo> List<Foo> foo;
8.11.2.3. Relationship to other annotations
@XmlJavaTypeAdapter
must be applied first
before any other mapping annotation is processed. Further annotation
processing is subject to their respective mapping constraints. For
example,
// PtoQAdapter is applied first and therefore converts type Q to P
// Next foo is mapped with a type of P (not Q) subject to the
// mapping constraints specified in@XmlElements.
@XmlJavaTypeAdapter(PtoQAdapter)
@XmlElements({
@XmlElement(name="x",type=PX.class),
@XmlElement(name="y",type=PY.class)
})
Q foo;
@XmlType abstract class P {}
@XmlType class PX extends P {}
@XmlType class PY extends P {}
8.11.2.4. Class Inheritance Semantics
When annotated on a class, the use of
@XmlJavaTypeAdapter
annotation is subject to the class inheritance
semantics described here. The semantics is described in terms of two
classes: a BaseClas
and a SubClass
that derives from BaseClass
.
There are two cases to consider:
-
@XmlJavaTypeAdapter
annotates theBaseClass
-
@XmlJavaTypeAdapter
annotates theSubClass
, a class that derives fromBaseClass
.
BaseClass: In this case, @XmlJavaTypeAdapter
annotates the BaseClass
. In this case, the marshalling and
unmarshalling of an instance of property or a field with a static type
of baseClass must follow the schema to which
XmlJavaTypeAdapter.value()
is mapped.
//Example: code fragment
@XmlJavaTypeAdapter(...) BaseClass {...}
public SubClass extends BaseClass {...}
public BaseClass foo;
public SubClass subFoo = new SubClass();
foo = subFoo;
In the absence of @XmlJavaTypeAdapter
annotation,
the instance of subFoo is marshalled with an xsi:type
:
<foo xsi:type="subClass"/>
With the @XmlJavaTypeAdapter
annotation,
however, the instance of subFoo
must be marshalled/unmarshalled
following the XML schema for @XmlJavaTypeAdapter.value()
.
Subclass: In this case, @XmlJavaTypeAdapter
annotates the SubClass
. By definition, the annotation does not cover
references to BaseClass
. Thus, the schema types to which SubClass
and
BaseClass
map are not in the same schema type hierarchy. Hence an
object with a static type of BaseClass
but containing an instance of
SubClass
can’t be marshalled or unmarshalled. An attempt to do so must
fail. For e.g,
// Example: Code fragment
BaseClass {...}
...
@XmlJavaTypeAdapter(...) SubClass extends BaseClass {...}
public class Bar {
public BaseClass foo;
public SubClass subFoo = new SubClass();
// marshal, unmarshal of foo will fail
foo = subFoo;
// marshal, unmarshal of subFoo will succeed
}
8.11.3. @XmlJavaTypeAdapters
This annotation is a container annotation for
defining multiple @XmlJavTypeAdapter
annotations at the package level.
8.11.3.1. Synopsis
@Retention(RUNTIME) @Target({PACKAGE})
public @interface XmlJavaTypeAdapters {
// Collection of @{@link XmlJavaTypeAdapter}annotations
XmlJavaTypeAdapter[] value();
}
8.11.3.2. Mapping
Each @XmlJavaTypeAdapter
annotation in
@XmlJavaTypeAdapters.value()
must be mapped as specified in
@XmlJavaTypeAdapter.
8.12. Default Mapping
This section describes the default mapping of program elements. The default mapping is specified in terms of default annotations that are considered to apply to a program element even in their absence.
8.12.1. Java Identifier To XML Name
The following is the default mapping for different identifiers:
-
class name: a class name is mapped to an XML name by de capitalization using
java.beans.Introspector.decapitalize(class name)
. -
enumtype name: enumtype name is mapped to an XML name by de capitalization using
java.beans.Introspector.decapitalize(enumtype name)
. -
A property name (e.g. address) is derived from JavaBean access method (e.g. getAddress) by JavaBean de capitalization of the JavaBean property name
java.beans.Introspector.decapitalize(JavaBeanAccessMethod)
8.12.2. Package
A package must be mapped with the following default package level mapping annotations:
-
@XmlAccessorType(jakarta.xml.bind.annotation.XmlAccessType.PUBLIC_MEMBER)
-
@XmlAccessorOrder(jakarta.xml.bind.annotation.XmlAccessOrder.UNDEFINED)
Design Note
Ordering of properties/fields based on source code order rather than alphabetical
order is more useful. However, at this time there is no portable way to specify
source code order. Order is undefined by Java reflection. Thus the default order
has been chosen to be |
-
@XmlSchema
8.12.3. Class
Unless @XmlTransient
annotation is present,
a class with a public or protected no-arg constructor must be mapped
with the following default mapping annotations: @XmlType
.
8.12.4. Enum type
An enum type must be mapped with the following default mapping annotations:
-
enum type declaration:
-
@XmlType
-
@XmlEnum
-
enum type {…}
-
-
each enum constant:
-
@XmlEnumValue (enumConstatEnum.name())
-
8.12.5. Property / Field
If the value of @XmlAccessorType.value()
is
jakarta.xml.bind.annotation.XmlAccessType.NONE
, then
-
properties and fields, unless explicitly annotated, must be considered to be annotated with
@XmlTransient
.
If the value of @XmlAccessorType.value()
is
jakarta.xml.bind.annotation.XmlAccessType.PROPERTY
, then
-
properties not explicitly annotated must be mapped; fields, unless explicitly annotated, must be considered to be annotated with
@XmlTransient
.
If the value of @XmlAccessorType.value()
is
jakarta.xml.bind.annotation.XmlAccessType.FIELD
, then
-
fields not explicitly annotated must be mapped; properties, unless explicitly annotated, must be considered to be annotated with
@XmlTransient
.
If the value of @XmlAccessorType.value()
is
jakarta.xml.bind.annotation.XmlAccessType.PUBLIC_MEMBER
, then
-
all properties and public fields, unless annotated with
@XmlTransient
, must be mapped.
See javadoc for
@jakarta.xml.bind.annotation.XmlAccessorType
for further information on
inheritance rules for this annotation.
8.12.5.1. Default Mapping
A property name (e.g. address) must be derived
from JavaBean access method (e.g. getAddress) by JavaBean
decapitalization of the JavaBean property name
java.beans.Introspector.decapitalize(JavaBeanAccessMethod)
A single valued property or field must be mapped with the following default mapping annotation:
-
@XmlElement
NoteAn alternative to mapping property or a field to an element by default is to map property or field to an attribute if its type maps to a XML Schema simple type. However, neither alternative is dominant. The default has been chosen to be
@XmlElement
.
A property or field with a collection type must be mapped by with the following default mapping annotation:
-
if the property or field is annotated with
@XmlList
, then the default mapping annotation is:@XmlElement
-
otherwise the default mapping annotation is:
@XmlElements( { @XmlElement(nillable=true)})
8.12.6. Map
By default, java.util.Map<K,V>
must be
mapped to the following anonymous schema type. The parameterized types K
and V must be mapped as specified in Type Arguments and Wildcards.
The anonymous schema type is at the
point of reference.
<!-- Default XML Schema mapping for Map<K,V> -->
<xs:complexType>
<xs:sequence>
<xs:element name="entry"
minOccurs =