The Marshaller class is responsible for governing the process
of serializing Java content trees back into XML data. It provides the basic
marshalling methods:
Assume the following setup code for all following code fragments:
JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
Unmarshaller u = jc.createUnmarshaller();
Object element = u.unmarshal( new File( "foo.xml" ) );
Marshaller m = jc.createMarshaller();
Marshalling to a File:
OutputStream os = new FileOutputStream( "nosferatu.xml" );
m.marshal( element, os );
Marshalling to a SAX ContentHandler:
// assume MyContentHandler instanceof ContentHandler
m.marshal( element, new MyContentHandler() );
Marshalling to a DOM Node:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
m.marshal( element, doc );
Marshalling to a java.io.OutputStream:
m.marshal( element, System.out );
Marshalling to a java.io.Writer:
m.marshal( element, new PrintWriter( System.out ) );
Marshalling to a javax.xml.transform.SAXResult:
// assume MyContentHandler instanceof ContentHandler
SAXResult result = new SAXResult( new MyContentHandler() );
m.marshal( element, result );
Marshalling to a javax.xml.transform.DOMResult:
DOMResult result = new DOMResult();
m.marshal( element, result );
Marshalling to a javax.xml.transform.StreamResult:
StreamResult result = new StreamResult( System.out );
m.marshal( element, result );
Marshalling to a javax.xml.stream.XMLStreamWriter:
XMLStreamWriter xmlStreamWriter =
XMLOutputFactory.newInstance().createXMLStreamWriter( ... );
m.marshal( element, xmlStreamWriter );
Marshalling to a javax.xml.stream.XMLEventWriter:
XMLEventWriter xmlEventWriter =
XMLOutputFactory.newInstance().createXMLEventWriter( ... );
m.marshal( element, xmlEventWriter );
Marshalling content tree rooted by a JAXB element
The first parameter of the overloadedMarshaller.marshal(java.lang.Object, ...)methods must be a JAXB element as computed byJAXBIntrospector#isElement(java.lang.Object); otherwise, aMarshaller.marshalmethod must throw aMarshalException. There exist two mechanisms to enable marshalling an instance that is not a JAXB element. One method is to wrap the instance as a value of aJAXBElement, and pass the wrapper element as the first parameter to aMarshaller.marshalmethod. For java to schema binding, it is also possible to simply annotate the instance's class with @XmlRootElement.
Encoding
By default, the Marshaller will use UTF-8 encoding when generating XML data to ajava.io.OutputStream, or ajava.io.Writer. Use thesetPropertyAPI to change the output encoding used during these marshal operations. Client applications are expected to supply a valid character encoding name as defined in the W3C XML 1.0 Recommendation and supported by your Java Platform.
Validation and Well-Formedness
Client applications are not required to validate the Java content tree prior to calling any of the marshal API's. Furthermore, 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. Different JAXB Providers will support marshalling invalid Java content trees at varying levels, however all JAXB Providers must be able to marshal a valid content tree back to XML data. A JAXB Provider must throw a
MarshalExceptionwhen it is unable to complete the marshal operation due to invalid content. Some JAXB Providers will fully allow marshalling invalid content, others will fail on the first validation error.Even when schema validation is not explictly enabled for the marshal operation, it is possible that certain types of validation events will be detected during the operation. Validation events will be reported to the registered event handler. If the client application has not registered an event handler prior to invoking one of the marshal API's, then events will be delivered to a default event handler which will terminate the marshal operation after encountering the first error or fatal error. Note that for JAXB 2.0 and later versions,
javax.xml.bind.helpers.DefaultValidationEventHandleris no longer used.
All JAXB Providers are required to support the following set of properties. Some providers may support additional properties.
jaxb.encoding- value must be a java.lang.String- The output encoding to use when marshalling the XML data. The Marshaller will use "UTF-8" by default if this property is not specified.
jaxb.formatted.output- value must be a java.lang.Boolean- This property controls whether or not the Marshaller will format the resulting XML data with line breaks and indentation. A true value for this property indicates human readable indented xml data, while a false value indicates unformatted xml data. The Marshaller will default to false (unformatted) if this property is not specified.
jaxb.schemaLocation- value must be a java.lang.String- This property allows the client application to specify an xsi:schemaLocation attribute in the generated XML data. The format of the schemaLocation attribute value is discussed in an easy to understand, non-normative form in Section 5.6 of the W3C XML Schema Part 0: Primer and specified in Section 2.6 of the W3C XML Schema Part 1: Structures.
jaxb.noNamespaceSchemaLocation- value must be a java.lang.String- This property allows the client application to specify an xsi:noNamespaceSchemaLocation attribute in the generated XML data. The format of the schemaLocation attribute value is discussed in an easy to understand, non-normative form in Section 5.6 of the W3C XML Schema Part 0: Primer and specified in Section 2.6 of the W3C XML Schema Part 1: Structures.
jaxb.fragment- value must be a java.lang.Boolean- This property determines whether or not document level events will be generated by the Marshaller. If the property is not specified, the default is
false. This property has different implications depending on which marshal api you are using - when this property is set to true:
marshal(Object,ContentHandler)- the Marshaller won't invokeorg.xml.sax.ContentHandler#startDocument()andorg.xml.sax.ContentHandler#endDocument().marshal(Object,Node)- the property has no effect on this API.marshal(Object,OutputStream)- the Marshaller won't generate an xml declaration.marshal(Object,Writer)- the Marshaller won't generate an xml declaration.marshal(Object,Result)- depends on the kind of Result object, see semantics for Node, ContentHandler, and Stream APIsmarshal(Object,XMLEventWriter)- the Marshaller will not generatejavax.xml.stream.events.XMLEvent#START_DOCUMENTandjavax.xml.stream.events.XMLEvent#END_DOCUMENTevents.marshal(Object,XMLStreamWriter)- the Marshaller will not generatejavax.xml.stream.events.XMLEvent#START_DOCUMENTandjavax.xml.stream.events.XMLEvent#END_DOCUMENTevents.
"TheMarshallerprovides 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 marshalling. 'External listeners' allow for centralized processing of marshal events in one callback method rather than by type event callbacks.Class defined event callback methods allow any JAXB mapped class to specify its own specific callback methods by defining methods with the following method signatures:
The class defined event callback methods should be used when the callback method requires access to non-public methods and/or fields of the class.// Invoked by Marshaller after it has created an instance of this object. boolean beforeMarshal(Marshaller); // Invoked by Marshaller after it has marshalled all properties of this object. void afterMarshal(Marshaller);The external listener callback mechanism enables the registration of a
Listenerinstance with aMarshaller#setListener(Listener). The external listener receives all callback events, allowing for more centralized processing than per class defined callback methods.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
Listener#beforeMarshal(Object)andListener#afterMarshal(Object).An event callback method throwing an exception terminates the current marshal process.
JAXBContext, Validator, Unmarshaller
| Modifier and Type | Class and Description |
|---|---|
| public abstract static class | Marshaller.Listener
Register an instance of an implementation of this class with a |
| Modifier and Type | Field and Description |
|---|---|
| public static final String | JAXB_ENCODING
The name of the property used to specify the output encoding in the marshalled XML data. |
| public static final String | JAXB_FORMATTED_OUTPUT
The name of the property used to specify whether or not the marshalled XML data is formatted with linefeeds and indentation. |
| public static final String | JAXB_FRAGMENT
The name of the property used to specify whether or not the marshaller will generate document level events (ie calling startDocument or endDocument). |
| public static final String | JAXB_NO_NAMESPACE_SCHEMA_LOCATION
The name of the property used to specify the xsi:noNamespaceSchemaLocation attribute value to place in the marshalled XML output. |
| public static final String | JAXB_SCHEMA_LOCATION
The name of the property used to specify the xsi:schemaLocation attribute value to place in the marshalled XML output. |
| Modifier and Type | Method and Description |
|---|---|
| public <A extends XmlAdapter> A | |
| public AttachmentMarshaller | |
| public ValidationEventHandler | Returns: the current ValidationEventHandler or the default event handler if it hasn't been setReturn the current event handler or the default event handler if one hasn't been set. |
| public Marshaller. | |
| public Node | |
| public Object | Returns: the value of the requested propertythe name of the property to retrieve name)Get the particular property in the underlying implementation of
|
| public Schema | |
| public void | |
| public void | marshal(Object
The root of content tree to be marshalled. jaxbElement, OutputStream XML will be added to this stream. os)Marshal the content tree rooted at |
| public void | |
| public void | |
| public void | marshal(Object
The root of content tree to be marshalled. jaxbElement, ContentHandler XML will be sent to this handler as SAX2 events. handler)Marshal the content tree rooted at |
| public void | marshal(Object
The content tree to be marshalled. jaxbElement, Node DOM nodes will be added as children of this node.
This parameter must be a Node that accepts children
( node)org.w3c.dom.Document,
org.w3c.dom.DocumentFragment, or
org.w3c.dom.Element)Marshal the content tree rooted at |
| public void | marshal(Object
The content tree to be marshalled. jaxbElement, XMLStreamWriter XML will be sent to this writer. writer)Marshal the content tree rooted at |
| public void | marshal(Object
The content tree rooted at jaxbElement to be marshalled. jaxbElement, XMLEventWriter XML will be sent to this writer. writer)Marshal the content tree rooted at |
| public void | setAdapter(XmlAdapter<ValueType, BoundType> adapter)
Associates a configured instance of |
| public <A extends XmlAdapter> void | setAdapter(Class<A>
The type of the adapter. The specified instance will be used when
type, A javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter#value()
refers to this type.The instance of the adapter to be used. If null, it will un-register
the current adapter set for this type. adapter)Associates a configured instance of |
| public void | setAttachmentMarshaller(AttachmentMarshaller am)
Associate a context that enables binary data within an XML document to be transmitted as XML-binary optimized attachment. |
| public void | setEventHandler(ValidationEventHandler
the validation event handler handler)Allow an application to register a validation event handler. |
| public void | setListener(Marshaller.
an instance of a class that implements listenerListener
Register marshal event callback |
| public void | setProperty(String
the name of the property to be set. This value can either
be specified using one of the constant fields or a user
supplied string. name, Object the value of the property to be set value)Set the particular property in the underlying implementation of
|
| public void |
| JAXB_ENCODING | back to summary |
|---|---|
| public static final String JAXB_ENCODING The name of the property used to specify the output encoding in the marshalled XML data. | |
| JAXB_FORMATTED_OUTPUT | back to summary |
|---|---|
| public static final String JAXB_FORMATTED_OUTPUT The name of the property used to specify whether or not the marshalled XML data is formatted with linefeeds and indentation. | |
| JAXB_FRAGMENT | back to summary |
|---|---|
| public static final String JAXB_FRAGMENT The name of the property used to specify whether or not the marshaller will generate document level events (ie calling startDocument or endDocument). | |
| JAXB_NO_NAMESPACE_SCHEMA_LOCATION | back to summary |
|---|---|
| public static final String JAXB_NO_NAMESPACE_SCHEMA_LOCATION The name of the property used to specify the xsi:noNamespaceSchemaLocation attribute value to place in the marshalled XML output. | |
| JAXB_SCHEMA_LOCATION | back to summary |
|---|---|
| public static final String JAXB_SCHEMA_LOCATION The name of the property used to specify the xsi:schemaLocation attribute value to place in the marshalled XML output. | |
| getAdapter | back to summary |
|---|---|
| public <A extends XmlAdapter> A getAdapter(Class<A> type) Gets the adapter associated with the specified type.
This is the reverse operation of the
| |
| getAttachmentMarshaller | back to summary |
|---|---|
| public AttachmentMarshaller getAttachmentMarshaller() | |
| getEventHandler | back to summary |
|---|---|
| public ValidationEventHandler getEventHandler() throws JAXBException Return the current event handler or the default event handler if one hasn't been set.
| |
| getListener | back to summary |
|---|---|
| public Marshaller. Return
| |
| getNode | back to summary |
|---|---|
| public Node getNode(Object contentTree) throws JAXBException Get a DOM tree view of the content tree(Optional).
If the returned DOM tree is updated, these changes are also
visible in the content tree.
Use
| |
| getProperty | back to summary |
|---|---|
| public Object getProperty(String name) throws PropertyException Get the particular property in the underlying implementation of
| |
| getSchema | back to summary |
|---|---|
| public Schema getSchema() Get the JAXP 1.3
| |
| marshal | back to summary |
|---|---|
| public void marshal(Object jaxbElement, Result result) throws JAXBException Marshal the content tree rooted at
All JAXB Providers must at least support
| |
| marshal | back to summary |
|---|---|
| public void marshal(Object jaxbElement, OutputStream os) throws JAXBException Marshal the content tree rooted at
| |
| marshal | back to summary |
|---|---|
| public void marshal(Object jaxbElement, File output) throws JAXBException Marshal the content tree rooted at
| |
| marshal | back to summary |
|---|---|
| public void marshal(Object jaxbElement, Writer writer) throws JAXBException Marshal the content tree rooted at
| |
| marshal | back to summary |
|---|---|
| public void marshal(Object jaxbElement, ContentHandler handler) throws JAXBException Marshal the content tree rooted at
| |
| marshal | back to summary |
|---|---|
| public void marshal(Object jaxbElement, Node node) throws JAXBException Marshal the content tree rooted at
| |
| marshal | back to summary |
|---|---|
| public void marshal(Object jaxbElement, XMLStreamWriter writer) throws JAXBException Marshal the content tree rooted at
| |
| marshal | back to summary |
|---|---|
| public void marshal(Object jaxbElement, XMLEventWriter writer) throws JAXBException Marshal the content tree rooted at
| |
| setAdapter | back to summary |
|---|---|
| public void setAdapter(XmlAdapter<ValueType, BoundType> adapter) Associates a configured instance of
This is a convenience method that invokes
| |
| setAdapter | back to summary |
|---|---|
| public <A extends XmlAdapter> void setAdapter(Class<A> type, A adapter) Associates a configured instance of
Every marshaller internally maintains a
This method allows applications to use a configured instance of
| |
| setAttachmentMarshaller | back to summary |
|---|---|
| public void setAttachmentMarshaller(AttachmentMarshaller am) Associate a context that enables binary data within an XML document to be transmitted as XML-binary optimized attachment. The attachment is referenced from the XML document content model by content-id URIs(cid) references stored within the xml document.
| |
| setEventHandler | back to summary |
|---|---|
| public void setEventHandler(ValidationEventHandler handler) throws JAXBException Allow an application to register a validation event handler. The validation event handler will be called by the JAXB Provider if any validation errors are encountered during calls to any of the marshal API's. If the client application does not register a validation event handler before invoking one of the marshal methods, then validation events will be handled by the default event handler which will terminate the marshal operation after the first error or fatal error is encountered. Calling this method with a null parameter will cause the Marshaller to revert back to the default default event handler.
| |
| setListener | back to summary |
|---|---|
| public void setListener(Marshaller.
Register marshal event callback
There is only one Listener per Marshaller. Setting a Listener replaces the previous set Listener.
One can unregister current Listener by setting listener to
| |
| setProperty | back to summary |
|---|---|
| public void setProperty(String name, Object value) throws PropertyException Set the particular property in the underlying implementation of
| |
| setSchema | back to summary |
|---|---|
| public void setSchema(Schema schema) Specify the JAXP 1.3 This method allows the caller to validate the marshalled XML as it's marshalled.
Initially this property is set to
| |
Register an instance of an implementation of this class with a Marshaller to externally listen
for marshal events.
This class enables pre and post processing of each marshalled object. The event callbacks are called when marshalling from an instance that maps to an xml element or complex type definition. The event callbacks are not called when marshalling from an instance of a Java datatype that represents a simple type definition.
External listener is one of two different mechanisms for defining marshal event callbacks. See Marshal Event Callbacks for an overview.
Marshaller#setListener(Listener), Marshaller#getListener()
| Access | Constructor and Description |
|---|---|
| public |
| Modifier and Type | Method and Description |
|---|---|
| public void | afterMarshal(Object
instance of JAXB mapped class after marshalling it. source)
Callback method invoked after marshalling |
| public void | beforeMarshal(Object
instance of JAXB mapped class prior to marshalling from it. source)
Callback method invoked before marshalling from |
| Listener | back to summary |
|---|---|
| public Listener() | |
| afterMarshal | back to summary |
|---|---|
| public void afterMarshal(Object source)
Callback method invoked after marshalling
This method is invoked after
| |
| beforeMarshal | back to summary |
|---|---|
| public void beforeMarshal(Object source)
Callback method invoked before marshalling from
This method is invoked just before marshalling process starts to marshal
| |