Java - Java API for XML Binding (JAXB) - (Un)Marshaller

About

JAXB is a serialization library (Java binding tool) between XML and Object.

It uses annotations to bind XML documents to a java object model.

Located under the javax.xml.bind package.

It generates Java code from a schema and you are able to transform from those classes into XML matching the processed schema and back.

Compiling an XML schema using the JAXB Binding Compiler xjc results in a set of classes that defines the types required for accessing elements, attributes and other content in a typesafe way.

The scalar datatypes of the XML Schema Language are mapped to Java data types.

JAXB uses Java's annotations for augmenting the generated classes with additional information that bridges the gap between what is decribed by an XML schema and the information available (via Java's reflection mechanisms) from a set of Java class definitions.

The code generated for a stand-alone element definition can be found in the class ObjectFactory which is generated along with all the classes derived from your schema's type definitions.

API

Entry Point

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 javax.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);
} 

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.

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 example, given the following Java classes:

@XmlRootElement class Foo { Bar b;}
@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.

The Unmarshaller class

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.

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.

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).

String

To unmarshall an XML document from a String you need to use the unmarshal method with the InputSource parameter and you had to use the constructor with a StringReader, because the constructor InputSource(String) has the meaning, that the argument is the URL of a file being loaded, not the actual file. See JaxmE

JAXBContext jc = JAXBContext.newInstance( ObjectFactory.class );
Unmarshaller unmarshaller = jc.createUnmarshaller();
Person person = (Person) unmarshaller.unmarshal(new InputSource(new StringReader(response)));

JAXB implementation

JAXBElement

JAXB has to use the JAXBElement<?> auxiliary type for elements if the schema has a complex element that contains a sequence consisting of elements with different tags but identical types.

Solution: You can always create distinct subtypes for each tag, even if the extension does not add anything.

Validation

Validation is the process of verifying that an xml document meets all the constraints expressed in the schema. 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 every IDREF

A document is valid if, and only if, all of the constraints expressed in its schema are satisfied.

package-info.java

Declaration of a global adapter for the String class. The package-info.java must be located in the same package than the schema (with the ObjectFactory.java class)

@XmlJavaTypeAdapters(
	 {@XmlJavaTypeAdapter(value=formatter.StringAdapter.class, type=String.class)}
)
package com.gerardnico.schema;

import javax.xml.bind.annotation.adapters.*;

Binding

JAXB Mapping of XML Schema Built-in Data Types

XML Schema Type Java Data Type
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
xsd:dateTime javax.xml.datatype.XMLGregorianCalendar
xsd:base64Binary byte[]
xsd:hexBinary byte[]
xsd:unsignedInt long
xsd:unsignedShort int
xsd:unsignedByte short
xsd:time javax.xml.datatype.XMLGregorianCalendar
xsd:date javax.xml.datatype.XMLGregorianCalendar
xsd:g javax.xml.datatype.XMLGregorianCalendar
xsd:anySimpleType java.lang.Object
xsd:anySimpleType java.lang.String
xsd:duration javax.xml.datatype.Duration
xsd:NOTATION javax.xml.namespace.QName

Documentation / Reference

Task Runner