O'Reilly logo

Java SOA Cookbook by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 particularly 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required