1 import javax.xml.transform.*;
2 import javax.xml.transform.stream.*;
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) {
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
26 public static String prettyFormat(String input) {
27 return formatXml(input, 2);
30 public static String readFile(String path, Charset encoding)
33 byte[] encoded = Files.readAllBytes(Paths.get(path));
34 return new String(encoded, encoding);
37 public static void main(String[] args){
39 if (args != null && args.length != 1){
40 System.out.println("Usage:java FormatXml xmlStr");
43 String xmlStr = readFile(args[0], StandardCharsets.UTF_8);
44 System.out.println(prettyFormat(xmlStr));