blob: 7c6915f7e363f5d4ba81e38d532f9d0372bc59bd [file] [log] [blame]
Timoney, Daniel (dt5972)324ee362017-02-15 10:37:53 -05001import javax.xml.transform.*;
2import javax.xml.transform.stream.*;
3import java.io.*;
4import java.util.*;
5import java.nio.file.Paths;
6import java.nio.file.Files;
7import java.nio.charset.StandardCharsets;
8import java.nio.charset.Charset;
9public class FormatXml{
10public 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
26public static String prettyFormat(String input) {
27 return formatXml(input, 2);
28}
29
30public 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
37public static void main(String[] args){
38try{
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}