DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document document = parser.parse(new ByteArrayInputStream(bos.toByteArray()));
DOMImplementationLS domImplementationLS = (DOMImplementationLS) document.getImplementation().getFeature("LS", "3.0");
LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
LSOutput lsOutput = domImplementationLS.createLSOutput();
lsOutput.setEncoding("UTF-8");
StringWriter stringWriter = new StringWriter();
lsOutput.setCharacterStream(stringWriter);