DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS domImplementation = (DOMImplementationLS) registry.getDOMImplementation("LS");
Writer stringWriter = new StringWriter();
LSOutput formattedOutput = domImplementation.createLSOutput();
formattedOutput.setCharacterStream(stringWriter);
LSSerializer domSerializer = domImplementation.createLSSerializer();
domSerializer.getDomConfig().setParameter("format-pretty-print", true);
// Set this to true if the declaration is needed to be in the output.
domSerializer.getDomConfig().setParameter("xml-declaration", keepXmlDeclaration);
domSerializer.write(document, formattedOutput);
return stringWriter.toString();