Last active
December 26, 2015 09:58
-
-
Save junkdog/7132864 to your computer and use it in GitHub Desktop.
toString-format XML documents for comparison purposes etc.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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