Java Reference
In-Depth Information
Converting a Java Object into an XML Document
Instance
Problem
You have a Java object that you want to convert into an XML document.
Solution
Use the JAXB Marshaler class and invoke its static marshal method.
Whether you have written your Java class from scratch or generated it from a schema, you can
use JAXB to write out a populated Java object to an XML representation. This representation
can take one of the following forms:
javax.io.Writer
javax.xml.stream.XMLStreamWriter
javax.xml.stream.XMLEventWriter
javax.xml.transform.Result
org.xml.sax.ContentHandler
org.w3.dom.Node
The variety of methods for handling the marshaling result gives you a lot of flexibility. You
can write the XML result out to a file, to a stream with StAX, as a transformation result, or
as a DOM node. Using the Node target is interesting, as it allows you to create the marshaled
object as a child on the specified node, using it as a fragment of that object. This can be par-
ticularly useful when assembling a SOAP body for a web service request.
You can't just start from a regular POJO (Plain Old Java Object) without annotations and
start marshaling. You need to have the appropriate JAXB XML annotations decorating your
Java class before you can do this. Recall that these are added automatically when you start
from a schema and then generate a Java class. If you have a POJO and you don't want to go
through building up from a schema, simply annotate your main composing object with the
XmlRootElement annotation, and you'll be on your way.
There are two ways to initialize the JAXBContext : using a list of package names or using a
class array. The first constructor accepts a string, which is a colon-separated list of package
names. Each name in the list must contain classes that are annotated with JAXB annotations,
Search WWH ::




Custom Search