I need to Marshal a JAXB object to xml format string. I'm using a SLSB and hook the code to create the Marshaller
and other things in @PostConstruct
annotated method. So that each time I need not load the schema and create the Marshaller.
The code in @PostConstruct
annotated method is as below.
JAXBContext jaxbContext = JAXBContext.newInstance(jaxbPackageName);
SchemaFactory factory = SchemaFactory
.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL schemaUrl = Thread.currentThread().getContextClassLoader()
.getResource(resourcePath);
schema = factory.newSchema(schemaUrl);
setMarshaller(jaxbContext.createMarshaller());
getMarshaller().setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.FALSE);
getMarshaller().setSchema(schema);
getMarshaller().setEventHandler(new DefaultValidationEventHandler());
setUnmarshaller(jaxbContext.createUnmarshaller());
getUnmarshaller().setSchema(schema);
getUnmarshaller().setEventHandler(new DefaultValidationEventHandler());
And when a client code needs xml format of the object the following method returns the same.
OutputStream outputStream = new ByteArrayOutputStream();
getMarshaller().setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
schemaLocation);
getMarshaller().marshal(document, outputStream);
xmlString = outputStream.toString();
My concern is, is there any better way to do the same (whenever a client code wants to get xml format of a JAXB object, the fastest approach to return the same? ).
Thanks