Marshalling

Marshalling is the process of mapping Java objects into XML documents. The binding APIs provide the Marshaller class that has a method called marshal. The marshal method outputs XML data corresponding to the content of a Java object. JAXB specifies the XML data in the stream specified by the second parameter to the marshal method.

The code snippet on the right displays the steps to marshal the XML document. Note that the steps are similar to the steps of the unmarshalling process. To marshal the XML document, you need to:

  • Create a JAXBContext object.
    The following statement creates a JAXBContext object:

  JAXBContext jc = JAXBContext.newInstance("customer");

  • Create a Marshaller object.
    The following statement creates a Marshaller object that controls the process of marshalling:

  Marshaller m = jc.createMarshaller();

  • Call the marshal method and specify methods to display the output.
    The marshal method maps the Java objects to XML documents. For example, the following declaration prints the XML document represented by the cust object:

  m.marshal( cust, System.out );

As a result, the following XML code is printed on the user console:

     <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
       <Customer>
         <FirstName>James</FirstName>
         <LastName>Gosling</LastName>
       </Customer>

Steps to Marshal an XML Document
----------------------------------------------

// Create a JAXBContext object
JAXBContext jc = JAXBContext.newInstance( "customer" );

// Create a Marshaller object
Marshaller m = jc.createMarshaller();

// Call the marshal method
m.marshal( cust, System.out );

Click the Next button to continue.