Tobias
Tobias

Reputation: 7380

Format XML with JAXB during unmarshal

I want to format a XML document during unmarshal with JAXB. Unmarshal looks like:

Unmarshaller u = createAndsetUpUnmarshaller(enableValidation, evtHandler, clazz);
return u.unmarshal(new ByteArrayInputStream(stringSource.getBytes()));

While marshaling one can format the code via:

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

But this isn´t possible for the unmarchal process... Any idea how I can format the XML string with JAXB during (or after) unmarshal process?

BTW: I read some posts here about pretty print, but I want to do it with JAXB!

Upvotes: 11

Views: 40009

Answers (4)

Justin Rowe
Justin Rowe

Reputation: 2456

If you want to log formatted XML corresponding to the XML that you just unmarshalled, you can simply remarshal the unmarshalled object back to XML, using the property you specified, ie.

/**
 * Marshall input object to a formatted XML String
 */
protected <T> String marshal(T input) throws JAXBException {
    StringWriter writer = new StringWriter();

    JAXBContext jc = JAXBContext.newInstance(input.getClass());
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(input, writer);
    return writer.toString();
}

On the other hand, if all you want to do is reformat the XML, you probably should be using JAXP instead of JAXB.

Upvotes: 26

Tony Nassar
Tony Nassar

Reputation: 1

One way to do this, if you insist, is to use an XSLT Transformer, such as Saxon's, that supports "teeing," i.e. lets you transform a Source to two Result objects. I don't know why you call String#getBytes(); you should be creating a StringReader and pulling from that. The two destinations for your "tee" would be the "identity transform" (the default if you call TransformerFactory#newTransformer()) and the other would be JAXBResult.

Upvotes: 0

subes
subes

Reputation: 1832

it is logically senseless to format the xml code while unmarshalling it?

Upvotes: 43

Isuru Sampath
Isuru Sampath

Reputation: 31

I think there is no pretty print for Unmarshaller because the result of the JAXB unmarshaller is not an XML but a Java object. If you want to pretty print the resulting unmarshalled object better override the toString() method of the jaxb generated object. (This will be a messy solution since each time you generate the JAX binding classes you will haveto introduce the toString() method yourself.

Hmmm... I hope the future versions of JAXB will have a solution to this shortcoming, since it is important for logging, etc.

Upvotes: 3

Related Questions