The Java Architecture for XML Binding (JAXB) provides a fast and convenient way to bind between XML schemas and Java representations, making it easy for Java developers to incorporate XML data and processing functions in Java applications. As part of this process, JAXB provides methods for unmarshalling XML instance documents into Java content trees, and then marshalling Java content trees back into XML instance documents. JAXB also provides a way to generate XML schema from Java objects.
Figure below shows the components that make up a JAXB implementation:
A JAXB implementation consists of the following architectural components:
Schema compiler: Binds a source schema to a set of schema-derived program elements. The binding is described by an XML-based binding language.
Schema generator: Maps a set of existing program elements to a derived schema. The mapping is described by program annotations.
Binding runtime framework: Provides unmarshalling (reading) and marshalling (writing) operations for accessing, manipulating, and validating XML content using either schema-derived or existing program elements.
Figure below shows what occurs during the JAXB binding process:
The general steps in the JAXB data binding process are:
Generate classes: An XML schema is used as input to the JAXB binding compiler to generate JAXB classes based on that schema.
Compile classes: All of the generated classes, source files, and application code must be compiled.
Unmarshal: XML documents written according to the constraints in the source schema are unmarshalled by the JAXB binding framework. Note that JAXB also supports unmarshalling XML data from sources other than files/documents, such as DOM nodes, string buffers, SAX Sources, and so forth.
Unmarshalling provides a client application the ability to convert XML data into JAXB-derived Java objects.
Generate content tree: The unmarshalling process generates a content tree of data objects instantiated from the generated JAXB classes; this content tree represents the structure and content of the source XML documents.
Validate (optional): The unmarshalling process optionally involves validation of the source XML documents before generating the content tree. Note that if you modify the content tree in Step 6, below, you can also use the JAXB Validate operation to validate the changes before marshalling the content back to an XML document.
Process content: The client application can modify the XML data represented by the Java content tree by means of interfaces generated by the binding compiler.
Marshal: The processed content tree is marshalled out to one or more XML output documents. The content may be validated before marshalling.
Marshalling provides a client application the ability to convert a JAXB-derived Java object tree back into XML data.
Unmarshalling
Generates content tree from XML document instance through JAXB binding framework.
Sources for unmarshalling can be:
Files/documents
InputStream
String buffers
DOM nodes
SAX Sources
javax.xml.bind.JAXBContext
provides an abstraction (entry point to the JAXB API) for managing the XML/Java
binding information necessary to implement the unmarshal, marshal and validate operations.
javax.xml.bind.JAXBContext
is created via newInstance(contextPath)
, where
contextPath
contains a list of Java package names that contain schema derived interfaces and classes.
JAXBContext jc = JAXBContext.newInstance("com.acme.foo:com.acme.bar");
Unmarshaller
, Marshaller
, Validator
object are created
from JAXBContext
object.
javax.xml.bind.Unmarshaller
is a Java interface. It governs the process of deserializing XML data
(XML document instance) into newly created Java content tree, optionally validates XML data as it is unmarshalled.
Unmarshalling from a File
:
// Create JAXBContext object JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); // Create Unmarshaller object Unmarshaller u = jc.createUnmarshaller(); // Unmarshall a XML document which is in the form of File Object o = u.unmarshal(new File("example.xml"));
Unmarshalling from an InputStream
:
InputStream is = new FileInputStream("example.xml"); JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); Object o = u.unmarshal(is);
Unmarshalling from a URL
:
JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); URL url = new URL("http://java.boot.by/example.xml"); Object o = u.unmarshal(url);
Unmarshalling from a StringBuffer
:
JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); StringBuffer xmlStr = new StringBuffer("<?xml version="1.0"?>..."); Object o = u.unmarshal(new StreamSource(new StringReader(xmlStr.toString())));
Unmarshalling from a org.w3c.dom.Node
:
JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new File("example.xml")); Object o = u.unmarshal(doc);
Unmarshalling from a javax.xml.transform.sax.SAXSource
:
XMLReader xmlReader = saxParser.getXMLReader(); SAXSource source = new SAXSource( xmlReader, new InputSource( "http://..." ) ); // Setup JAXB to unmarshal JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); ValidationEventCollector vec = new ValidationEventCollector(); u.setEventHandler(vec); // turn off the JAXB provider's default validation mechanism to // avoid duplicate validation u.setValidating(false); // unmarshal Object o = u.unmarshal(source);
Turning off validation during unmarshalling:
JAXBContext jc = JAXBContext.newInstance("com.acme.foo");
Unmarshaller u = jc.createUnmarshaller();
u.setValidating(false);
Object o = u.unmarshal(new File("example.xml"));
Marshalling
Content tree may be marshalled by passing it to marshal
method of Marshaller
object,
content trees are no longer required to be valid before marshalling.
javax.xml.bind.Marshaller
is a Java interface, it governs the process of serializing Java content trees
back into XML data.
Marshalling to a File
:
JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); FooObject obj = (FooObject)u.unmarshal(new File("foo.xml")); Marshaller m = jc.createMarshaller(); OutputStream os = new FileOutputStream("newFoo.xml"); m.marshal(obj, os);
Marshalling to a SAX ContentHandler
:
JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); FooObject obj = (FooObject)u.unmarshal(new File("foo.xml")); Marshaller m = jc.createMarshaller(); // assume MyContentHandler instanceof ContentHandler m.marshal(obj, new MyContentHandler());
Marshalling to a DOM Node
:
JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); FooObject obj = (FooObject)u.unmarshal(new File("foo.xml")); Marshaller m = jc.createMarshaller(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); m.marshal(obj, doc);
Marshalling to a java.io.OutputStream
:
JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); FooObject obj = (FooObject)u.unmarshal(new File("foo.xml")); Marshaller m = jc.createMarshaller(); m.marshal(obj, System.out);
Marshalling to a java.io.Writer
:
JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); FooObject obj = (FooObject)u.unmarshal(new File("foo.xml")); Marshaller m = jc.createMarshaller(); m.marshal(obj, new PrintWriter(System.out));
Marshalling to a javax.xml.transform.SAXResult
:
JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); FooObject obj = (FooObject)u.unmarshal(new File("foo.xml")); Marshaller m = jc.createMarshaller(); // assume MyContentHandler instanceof ContentHandler SAXResult result = new SAXResult(new MyContentHandler()); m.marshal(obj, result);
Marshalling to a javax.xml.transform.DOMResult
:
JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); FooObject obj = (FooObject)u.unmarshal(new File("foo.xml")); Marshaller m = jc.createMarshaller(); DOMResult result = new DOMResult(); m.marshal(obj, result);
Marshalling to a javax.xml.transform.StreamResult
:
JAXBContext jc = JAXBContext.newInstance("com.acme.foo"); Unmarshaller u = jc.createUnmarshaller(); FooObject obj = (FooObject)u.unmarshal(new File("foo.xml")); Marshaller m = jc.createMarshaller(); StreamResult result = new StreamResult(System.out); m.marshal(obj, result);
Validation
Forms of validation:
Fail-fast Validation: Simple runtime type constraint check that can be performed by property setter method.
On-Demand Validation: Applications can call the Validator.validate
method on the
Java content tree (or any sub-tree of it):
JaxbContext jaxbCtx = JaxbContext.newInstance("generated.packageName"); Unmarshaller um = jaxbCtx.createUnmarshaller(); Trade trade = (Trade)um.unmarshal(inputStream); String symbol = trade.getSymbol(); float price = trace.getPrice(); if (symbol.equals("WIDGETS") && price > 10.00) { trade.setQuantity(30); } Validator validator = jaxbCtx.createValidator(); validator.validate(trade); Marshaller m = jaxbCtx.createMarshaller(); m.marshal(outputStream, trade);
Validation during Unmarshalling.
Deprecated approach:
JAXBContext jc = JAXBContext.newInstance("by.boot.java"); // An Unmarshaller instance is created. Unmarshaller u = jc.createUnmarshaller(); // The default JAXB Unmarshaller ValidationEventHandler is enabled // to send to validation warnings and errors to System.out. The // default configuration causes the unmarshal operation to fail // upon encountering the first validation error. u.setValidating(true);
Recommended approach:
JAXBContext jc = JAXBContext.newInstance("by.boot.java"); // An Unmarshaller instance is created. Unmarshaller u = jc.createUnmarshaller(); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new StreamSource(new File("schemaFile.xsd"))); // This sets us up for validation u.setSchema(schema);
![]() |
![]() ![]() |