1

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

nobody
  • 1,909
  • 5
  • 31
  • 45

2 Answers2

3

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

Valchev
  • 1,490
  • 14
  • 17
  • Hooking the initializing code to @PostConstruct wouldn't cause any issues right ? I mean sessions getting mixed during consecutive calls, if the object to be marshalled is passed as a parameter ? – nobody Dec 19 '11 at 14:34
  • Check the provided link. I think it probably provides better answer to your question. – Valchev Dec 19 '11 at 14:39
1

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.

jarnbjo
  • 33,923
  • 7
  • 70
  • 94