Interface Marshaller
- All Known Implementing Classes:
AbstractMarshallerImpl
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 Jakarta XML Binding element
The first parameter of the overloadedMarshaller.marshal(java.lang.Object, ...)
methods must be a Jakarta XML Binding element as computed byJAXBIntrospector.isElement(java.lang.Object)
; otherwise, aMarshaller.marshal
method must throw aMarshalException
. There exist two mechanisms to enable marshalling an instance that is not a Jakarta XML Binding element. One method is to wrap the instance as a value of aJAXBElement
, and pass the wrapper element as the first parameter to aMarshaller.marshal
method. 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 thesetProperty
API 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 Jakarta XML Binding Providers will support marshalling invalid Java content trees at varying levels, however all Jakarta XML Binding Providers must be able to marshal a valid content tree back to XML data. A Jakarta XML Binding Provider must throw a
MarshalException
when it is unable to complete the marshal operation due to invalid content. Some Jakarta XML Binding 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 Jakarta XML Binding and later versions,
DefaultValidationEventHandler
is no longer used.
All Jakarta XML Binding 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 invokeContentHandler.startDocument()
andContentHandler.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 generateXMLStreamConstants.START_DOCUMENT
andXMLStreamConstants.END_DOCUMENT
events.marshal(Object,XMLStreamWriter)
- the Marshaller will not generateXMLStreamConstants.START_DOCUMENT
andXMLStreamConstants.END_DOCUMENT
events.
"TheMarshaller
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 Jakarta XML Binding 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 Jakarta XML Binding 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
Marshaller.Listener
instance with asetListener(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
Marshaller.Listener.beforeMarshal(Object)
andMarshaller.Listener.afterMarshal(Object)
.An event callback method throwing an exception terminates the current marshal process.
- Since:
- 1.6, JAXB 1.0
- See Also:
-
Nested Class Summary
Modifier and TypeInterfaceDescriptionstatic class
Register an instance of an implementation of this class with aMarshaller
to externally listen for marshal events. -
Field Summary
Modifier and TypeFieldDescriptionstatic final String
The name of the property used to specify the output encoding in the marshalled XML data.static final String
The name of the property used to specify whether or not the marshalled XML data is formatted with linefeeds and indentation.static final String
The name of the property used to specify whether or not the marshaller will generate document level events (ie calling startDocument or endDocument).static final String
The name of the property used to specify the xsi:noNamespaceSchemaLocation attribute value to place in the marshalled XML output.static final String
The name of the property used to specify the xsi:schemaLocation attribute value to place in the marshalled XML output. -
Method Summary
Modifier and TypeMethodDescription<A extends XmlAdapter>
AgetAdapter
(Class<A> type) Gets the adapter associated with the specified type.Return the current event handler or the default event handler if one hasn't been set.ReturnMarshaller.Listener
registered with thisMarshaller
.Get a DOM tree view of the content tree(Optional).getProperty
(String name) Get the particular property in the underlying implementation ofMarshaller
.Get the JAXP 1.3Schema
object being used to perform marshal-time validation.void
Marshal the content tree rooted atjaxbElement
into a file.void
marshal
(Object jaxbElement, OutputStream os) Marshal the content tree rooted atjaxbElement
into an output stream.void
Marshal the content tree rooted atjaxbElement
into a Writer.void
marshal
(Object jaxbElement, XMLEventWriter writer) Marshal the content tree rooted atjaxbElement
into aXMLEventWriter
.void
marshal
(Object jaxbElement, XMLStreamWriter writer) Marshal the content tree rooted atjaxbElement
into aXMLStreamWriter
.void
Marshal the content tree rooted atjaxbElement
into the specifiedjavax.xml.transform.Result
.void
Marshal the content tree rooted atjaxbElement
into a DOM tree.void
marshal
(Object jaxbElement, ContentHandler handler) Marshal the content tree rooted atjaxbElement
into SAX2 events.void
setAdapter
(XmlAdapter adapter) Associates a configured instance ofXmlAdapter
with this marshaller.<A extends XmlAdapter>
voidsetAdapter
(Class<A> type, A adapter) Associates a configured instance ofXmlAdapter
with this marshaller.void
Associate a context that enables binary data within an XML document to be transmitted as XML-binary optimized attachment.void
setEventHandler
(ValidationEventHandler handler) Allow an application to register a validation event handler.void
setListener
(Marshaller.Listener listener) Register marshal event callbackMarshaller.Listener
with thisMarshaller
.void
setProperty
(String name, Object value) Set the particular property in the underlying implementation ofMarshaller
.void
Specify the JAXP 1.3Schema
object that should be used to validate subsequent marshal operations against.
-
Field Details
-
JAXB_ENCODING
The name of the property used to specify the output encoding in the marshalled XML data.- See Also:
-
JAXB_FORMATTED_OUTPUT
The name of the property used to specify whether or not the marshalled XML data is formatted with linefeeds and indentation.- See Also:
-
JAXB_SCHEMA_LOCATION
The name of the property used to specify the xsi:schemaLocation attribute value to place in the marshalled XML output.- See Also:
-
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.- See Also:
-
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).- See Also:
-
-
Method Details
-
marshal
Marshal the content tree rooted atjaxbElement
into the specifiedjavax.xml.transform.Result
.All Jakarta XML Binding Providers must at least support
DOMResult
,SAXResult
, andStreamResult
. It can support other derived classes ofResult
as well.- Parameters:
jaxbElement
- The root of content tree to be marshalled.result
- XML will be sent to this Result- Throws:
JAXBException
- If any unexpected problem occurs during the marshalling.MarshalException
- If theValidationEventHandler
returns false from itshandleEvent
method or theMarshaller
is unable to marshaljaxbElement
(or any object reachable fromjaxbElement
). See Marshalling a Jakarta XML Binding element.IllegalArgumentException
- If any of the method parameters are null
-
marshal
Marshal the content tree rooted atjaxbElement
into an output stream.- Parameters:
jaxbElement
- The root of content tree to be marshalled.os
- XML will be added to this stream.- Throws:
JAXBException
- If any unexpected problem occurs during the marshalling.MarshalException
- If theValidationEventHandler
returns false from itshandleEvent
method or theMarshaller
is unable to marshaljaxbElement
(or any object reachable fromjaxbElement
). See Marshalling a Jakarta XML Binding element.IllegalArgumentException
- If any of the method parameters are null
-
marshal
Marshal the content tree rooted atjaxbElement
into a file.- Parameters:
jaxbElement
- The root of content tree to be marshalled.output
- File to be written. If this file already exists, it will be overwritten.- Throws:
JAXBException
- If any unexpected problem occurs during the marshalling.MarshalException
- If theValidationEventHandler
returns false from itshandleEvent
method or theMarshaller
is unable to marshaljaxbElement
(or any object reachable fromjaxbElement
). See Marshalling a Jakarta XML Binding element.IllegalArgumentException
- If any of the method parameters are null- Since:
- 1.6, JAXB 2.1
-
marshal
Marshal the content tree rooted atjaxbElement
into a Writer.- Parameters:
jaxbElement
- The root of content tree to be marshalled.writer
- XML will be sent to this writer.- Throws:
JAXBException
- If any unexpected problem occurs during the marshalling.MarshalException
- If theValidationEventHandler
returns false from itshandleEvent
method or theMarshaller
is unable to marshaljaxbElement
(or any object reachable fromjaxbElement
). See Marshalling a Jakarta XML Binding element.IllegalArgumentException
- If any of the method parameters are null
-
marshal
Marshal the content tree rooted atjaxbElement
into SAX2 events.- Parameters:
jaxbElement
- The root of content tree to be marshalled.handler
- XML will be sent to this handler as SAX2 events.- Throws:
JAXBException
- If any unexpected problem occurs during the marshalling.MarshalException
- If theValidationEventHandler
returns false from itshandleEvent
method or theMarshaller
is unable to marshaljaxbElement
(or any object reachable fromjaxbElement
). See Marshalling a Jakarta XML Binding element.IllegalArgumentException
- If any of the method parameters are null
-
marshal
Marshal the content tree rooted atjaxbElement
into a DOM tree.- Parameters:
jaxbElement
- The content tree to be marshalled.node
- DOM nodes will be added as children of this node. This parameter must be a Node that accepts children (Document
,DocumentFragment
, orElement
)- Throws:
JAXBException
- If any unexpected problem occurs during the marshalling.MarshalException
- If theValidationEventHandler
returns false from itshandleEvent
method or theMarshaller
is unable to marshaljaxbElement
(or any object reachable fromjaxbElement
). See Marshalling a Jakarta XML Binding element.IllegalArgumentException
- If any of the method parameters are null
-
marshal
Marshal the content tree rooted atjaxbElement
into aXMLStreamWriter
.- Parameters:
jaxbElement
- The content tree to be marshalled.writer
- XML will be sent to this writer.- Throws:
JAXBException
- If any unexpected problem occurs during the marshalling.MarshalException
- If theValidationEventHandler
returns false from itshandleEvent
method or theMarshaller
is unable to marshaljaxbElement
(or any object reachable fromjaxbElement
). See Marshalling a Jakarta XML Binding element.IllegalArgumentException
- If any of the method parameters are null- Since:
- 1.6, JAXB 2.0
-
marshal
Marshal the content tree rooted atjaxbElement
into aXMLEventWriter
.- Parameters:
jaxbElement
- The content tree rooted at jaxbElement to be marshalled.writer
- XML will be sent to this writer.- Throws:
JAXBException
- If any unexpected problem occurs during the marshalling.MarshalException
- If theValidationEventHandler
returns false from itshandleEvent
method or theMarshaller
is unable to marshaljaxbElement
(or any object reachable fromjaxbElement
). See Marshalling a Jakarta XML Binding element.IllegalArgumentException
- If any of the method parameters are null- Since:
- 1.6, JAXB 2.0
-
getNode
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. Usemarshal(Object, org.w3c.dom.Node)
to force a deep copy of the content tree to a DOM representation.- Parameters:
contentTree
- - Jakarta XML Binding Java representation of XML content- Returns:
- the DOM tree view of the contentTree
- Throws:
UnsupportedOperationException
- If the Jakarta XML Binding provider implementation does not support a DOM view of the content treeIllegalArgumentException
- If any of the method parameters are nullJAXBException
- If any unexpected problem occurs
-
setProperty
Set the particular property in the underlying implementation ofMarshaller
. This method can only be used to set one of the standard Jakarta XML Binding defined properties above or a provider specific property. Attempting to set an undefined property will result in a PropertyException being thrown. See Supported Properties.- Parameters:
name
- 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.value
- the value of the property to be set- Throws:
PropertyException
- when there is an error processing the given property or valueIllegalArgumentException
- If the name parameter is null
-
getProperty
Get the particular property in the underlying implementation ofMarshaller
. This method can only be used to get one of the standard Jakarta XML Binding defined properties above or a provider specific property. Attempting to get an undefined property will result in a PropertyException being thrown. See Supported Properties.- Parameters:
name
- the name of the property to retrieve- Returns:
- the value of the requested property
- Throws:
PropertyException
- when there is an error retrieving the given property or value property nameIllegalArgumentException
- If the name parameter is null
-
setEventHandler
Allow an application to register a validation event handler.The validation event handler will be called by the Jakarta XML Binding 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.
- Parameters:
handler
- the validation event handler- Throws:
JAXBException
- if an error was encountered while setting the event handler
-
getEventHandler
Return the current event handler or the default event handler if one hasn't been set.- Returns:
- the current ValidationEventHandler or the default event handler if it hasn't been set
- Throws:
JAXBException
- if an error was encountered while getting the current event handler
-
setAdapter
Associates a configured instance ofXmlAdapter
with this marshaller.This is a convenience method that invokes
setAdapter(adapter.getClass(),adapter);
.- Throws:
IllegalArgumentException
- if the adapter parameter is null.UnsupportedOperationException
- if invoked agains a JAXB 1.0 implementation.- Since:
- 1.6, JAXB 2.0
- See Also:
-
setAdapter
Associates a configured instance ofXmlAdapter
with this marshaller.Every marshaller internally maintains a
Map
<Class
,XmlAdapter
>, which it uses for marshalling classes whose fields/methods are annotated withXmlJavaTypeAdapter
.This method allows applications to use a configured instance of
XmlAdapter
. When an instance of an adapter is not given, a marshaller will create one by invoking its default constructor.- Parameters:
type
- The type of the adapter. The specified instance will be used whenXmlJavaTypeAdapter.value()
refers to this type.adapter
- The instance of the adapter to be used. If null, it will un-register the current adapter set for this type.- Throws:
IllegalArgumentException
- if the type parameter is null.UnsupportedOperationException
- if invoked agains a JAXB 1.0 implementation.- Since:
- 1.6, JAXB 2.0
-
getAdapter
Gets the adapter associated with the specified type. This is the reverse operation of thesetAdapter(jakarta.xml.bind.annotation.adapters.XmlAdapter)
method.- Throws:
IllegalArgumentException
- if the type parameter is null.UnsupportedOperationException
- if invoked agains a JAXB 1.0 implementation.- Since:
- 1.6, JAXB 2.0
-
setAttachmentMarshaller
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.
- Throws:
IllegalStateException
- if attempt to concurrently call this method during a marshal operation.
-
getAttachmentMarshaller
AttachmentMarshaller getAttachmentMarshaller() -
setSchema
Specify the JAXP 1.3Schema
object that should be used to validate subsequent marshal operations against. Passing null into this method will disable validation.This method allows the caller to validate the marshalled XML as it's marshalled.
Initially this property is set to
null
.- Parameters:
schema
- Schema object to validate marshal operations against or null to disable validation- Throws:
UnsupportedOperationException
- could be thrown if this method is invoked on an Marshaller created from a JAXBContext referencing JAXB 1.0 mapped classes- Since:
- 1.6, JAXB 2.0
-
getSchema
Schema getSchema()Get the JAXP 1.3Schema
object being used to perform marshal-time validation. If there is no Schema set on the marshaller, then this method will return null indicating that marshal-time validation will not be performed.- Returns:
- the Schema object being used to perform marshal-time validation or null if not present.
- Throws:
UnsupportedOperationException
- could be thrown if this method is invoked on an Marshaller created from a JAXBContext referencing JAXB 1.0 mapped classes- Since:
- 1.6, JAXB 2.0
-
setListener
Register marshal event callback
Marshaller.Listener
with thisMarshaller
.There is only one Listener per Marshaller. Setting a Listener replaces the previous set Listener. One can unregister current Listener by setting listener to
null
.- Parameters:
listener
- an instance of a class that implementsMarshaller.Listener
- Since:
- 1.6, JAXB 2.0
-
getListener
Marshaller.Listener getListener()Return
Marshaller.Listener
registered with thisMarshaller
.- Returns:
- registered
Marshaller.Listener
ornull
if no Listener is registered with this Marshaller. - Since:
- 1.6, JAXB 2.0
-