Skip to content

Instantly share code, notes, and snippets.

@liyuntao
Last active August 29, 2015 14:15
Show Gist options
  • Save liyuntao/74d1ae93f340fa2e5861 to your computer and use it in GitHub Desktop.
Save liyuntao/74d1ae93f340fa2e5861 to your computer and use it in GitHub Desktop.
public static String format(String unformattedXml) {
try {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
writer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE);
LSOutput output = impl.createLSOutput();
ByteArrayOutputStream out = new ByteArrayOutputStream();
output.setByteStream(out);
writer.write(parseXmlFile(unformattedXml), output);
String xmlStr = new String(out.toByteArray(), "UTF-8"); // Charset is extremely important
return xmlStr;
} catch (Exception e) {
return unformattedXml;
}
}
private static Document parseXmlFile(String in) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(in));
return db.parse(is);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment