How to Customize the Serialization / use JAXB 2.0
Using the methods JAXB.marshal and JAXB.unmarshall, as shown in the previous sections, is the most convenient way of using JAXB. Unfortunately, they do no allow any customization of the serialization and deserialization processes, and they are not available JAXB 2.0. In order to get around these limitations, you have to work with the JAXBContext, Marshaller and Unmarshaller objects.
The following example shows you how to write a Java object into an XML document using Marshaller:
MovieLibrary library = ...;
JAXBContext ctx = JAXBContext.newInstance(MovieLibrary.class); // create JAXBContext (more)
Marshaller marshaller = ctx.createMarshaller();
marshaller.marshal(library, new FileOutputStream("/tmp/library.xml"));
Note that the example above only works if you declared the @XmlRootElement for the MovieLibrary class. This shouldn't be a problem for classes you wrote yourself. However, the xjc compiler does not set it automatically under some circumstances (more). In this case you must set the root element's name explicitly and the marshal call looks like this:
marshaller.marshal(new JAXBElement<MovieLibrary>(new QName("movieLibrary"),
MovieLibrary.class, library),
new FileOutputStream("/tmp/library.xml"));
Loading XML with the Unmarshaller is similar to storing:
JAXBContext ctx = JAXBContext.newInstance(MovieLibrary.class); // can be reused
Unmarshaller unmarshaller = ctx.createUnmarshaller();
MovieLibrary library = unmarshaller.unmarshal(new StreamSource(new File("/tmp/library.xml")),
MovieLibrary.class).getValue();

