JAXB Marshaller indentation

This annoying issue could be fixed by applying javax Transformer to the output.

import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.StreamResult;

Object jaxbElement = // The object you want to marshall using jaxb.

JAXBContext context = JAXBContext.newInstance(jaxbElement.getClass());
Marshaller marshaller = context.createMarshaller();
OutputStream out = // Here your destination, FileOutStream, ByteOutStream etc
DOMResult domResult = new DOMResult();
marshaller.marshal(jaxbElement, domResult);

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(new DOMSource(domResult.getNode()), new StreamResult(out));

This in an JAXB error, at most 8 levels of indentation are hardcoded:


    private void printIndent() throws IOException {
        int i = depth%8;
        write( indent8.buf, 0, i*unitLen );
        i>>=3;  // really i /= 8;
        for( ; i>0; i-- )

Source: https://community.oracle.com/thread/2351779