Format XML with JAXB during unmarshal Format XML with JAXB during unmarshal xml xml

Format XML with JAXB during unmarshal


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


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.


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.