1
votes

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

2

2 Answers

3
votes

I don't know any other way of marshalling/unmarshalling with JAXB. When I had the same problem, I checked the CXF code and it was the same.

Refer to JAXB Performance and Thread safety

1
votes

Not directly related to your question, but ByteArrayOutputStream#toString() will use the platform's default character encoding and not the encoding used by JAXB when creating the XML document. Depending on your further plans with the XML document, it might be better to keep it as a byte array instead of trying to make a potentially incorrect String out of it.