This exact question has been answered some months ago and one of the answers is to use the IndentingXMLStreamWriter class:
XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
XMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(out));
It is a neat solution as far as the code goes, but careful: this is a com.sun.* class, there is no guarantee of its general availability…