DOMImplementationRegistry domReg = DOMImplementationRegistry.newInstance();
DOMImplementationLS lsImpl = (DOMImplementationLS) domReg.getDOMImplementation("LS");
LSSerializer lsSerializer = lsImpl.createLSSerializer();
lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
LSOutput output = lsImpl.createLSOutput();
output.setEncoding("UTF-8");
StringWriter destination = new StringWriter();
output.setCharacterStream(destination);
lsSerializer.write(doc, output);
return destination.toString();
} catch (Exception e) {
// format failed, return unformatted xml
return unformattedXml;