Timoney, Daniel (dt5972) | 324ee36 | 2017-02-15 10:37:53 -0500 | [diff] [blame] | 1 | import javax.xml.transform.*; |
| 2 | import javax.xml.transform.stream.*; |
| 3 | import java.io.*; |
| 4 | import java.util.*; |
| 5 | import java.nio.file.Paths; |
| 6 | import java.nio.file.Files; |
| 7 | import java.nio.charset.StandardCharsets; |
| 8 | import java.nio.charset.Charset; |
| 9 | public class FormatXml{ |
| 10 | public static String formatXml(String input, int indent) { |
| 11 | try { |
| 12 | Source xmlInput = new StreamSource(new StringReader(input)); |
| 13 | StringWriter stringWriter = new StringWriter(); |
| 14 | StreamResult xmlOutput = new StreamResult(stringWriter); |
| 15 | TransformerFactory transformerFactory = TransformerFactory.newInstance(); |
| 16 | transformerFactory.setAttribute("indent-number", indent); |
| 17 | Transformer transformer = transformerFactory.newTransformer(); |
| 18 | transformer.setOutputProperty(OutputKeys.INDENT, "yes"); |
| 19 | transformer.transform(xmlInput, xmlOutput); |
| 20 | return xmlOutput.getWriter().toString(); |
| 21 | } catch (Exception e) { |
| 22 | throw new RuntimeException(e); // simple exception handling, please review it |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | public static String prettyFormat(String input) { |
| 27 | return formatXml(input, 2); |
| 28 | } |
| 29 | |
| 30 | public static String readFile(String path, Charset encoding) |
| 31 | throws IOException |
| 32 | { |
| 33 | byte[] encoded = Files.readAllBytes(Paths.get(path)); |
| 34 | return new String(encoded, encoding); |
| 35 | } |
| 36 | |
| 37 | public static void main(String[] args){ |
| 38 | try{ |
| 39 | if (args != null && args.length != 1){ |
| 40 | System.out.println("Usage:java FormatXml xmlStr"); |
| 41 | System.exit(-1); |
| 42 | } |
| 43 | String xmlStr = readFile(args[0], StandardCharsets.UTF_8); |
| 44 | System.out.println(prettyFormat(xmlStr)); |
| 45 | }catch(Exception e){ |
| 46 | e.printStackTrace(); |
| 47 | } |
| 48 | } |
| 49 | } |