Only a handful of source code lines was required to make a JAXB Marshaller
object write a document tree as an XML file. First you obtain a from Marshaller
a JAXBContext
. Then, you might set a number of properties, such as the one that's used below, which requests nice formatting of the XML t Ext. Other properties concern the inclusion of a schema location as an attribute in the top-level element, or the encoding in T He XML Prolog. The first argument must are an object, a root element of either a, as defined by your schema, or a JAXBElement<?>
.
import java.io.* import javax.xml.bind.* Writedocument (Object document, String pathname) throws Jaxbexception, IOException {Class <T> clazz = Document.getvalue (). GetClass (); Jaxbcontext context = jaxbcontext.newinstance (Clazz.getpackage (). GetName ()); Marshaller m = Context.createmarshaller (); M.setproperty (Marshaller.jaxb_formatted_output, boolean.true); M.marshal (document, new FileOutputStream (pathname));}
Sometimes marshalling needs to be do not only for one or both root documents but for obj ECTs of many different schema types . Could, of course, add xsd:element
definitions for all of them to the top level xsd:s Chema
element, but the is cumbersome. A generic solution is presented below. the method wraps an arbitrary element of some type T
into a < Code>jaxbelement<t> .
<T> jaxbelement<t> wrap (string ns, string tag, T o) {QName Qtag = new QName (ns, tag); Class <?> clazz = O.getclass (); @SuppressWarnings ( "Unchecked" ) jaxbelement <T> jbe = new Jaxbelement (Qtag, Clazz, O); return Jbe;}
To use it, you must create a context capable of handling all the classes that might crop up as instantiations for T
. Creating A for JAXBContext
several packages or classes are explained in section the JAXB Context.) With a Marshaller m
obtained from this context, the application of was as simple as this wrap
:
SomeType st = ...; Jaxbelement"http://www.acme.com", "Sometag", St); M.marshal (JBX, System.out);
Jaxb-calling Marshal