Last active
August 29, 2015 14:15
-
-
Save liyuntao/74d1ae93f340fa2e5861 to your computer and use it in GitHub Desktop.
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 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