Skip to content

Instantly share code, notes, and snippets.

@junkdog
Last active December 26, 2015 09:58
Show Gist options
  • Save junkdog/7132864 to your computer and use it in GitHub Desktop.
Save junkdog/7132864 to your computer and use it in GitHub Desktop.
toString-format XML documents for comparison purposes etc.
public final class XmlUtil
{
public static String formatXml(Document document)
throws Exception
{
// the DocumentBuilderFactory can't reliably be configured to produce
// identical output from semantically identical documents, contrary to what
// its methods would suggest. Hence:
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
LSOutput output = impl.createLSOutput();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
output.setByteStream(baos);
writer.write(document, output);
return baos.toString("UTF-8");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment