How to format or indent an xml string
The following method indents xml using 4 spaces (per indention/tab).
public static String toFormattedXml(String xml) {
try {
XmlOptions options = new XmlOptions();
options.setSavePrettyPrint();
options.setSavePrettyPrintIndent(4);
XmlObject formatter = XmlObject.Factory.parse(xml, options);
byte[] byteArray = xml.getBytes();
ByteArrayOutputStream out = new ByteArrayOutputStream(byteArray.length);
formatter.save(out, options);
return out.toString();
} catch (IOException e) {
System.err.println("IOException while creating ByteArrayOutputStream for formatting xml.", e);
}
}
try {
XmlOptions options = new XmlOptions();
options.setSavePrettyPrint();
options.setSavePrettyPrintIndent(4);
XmlObject formatter = XmlObject.Factory.parse(xml, options);
byte[] byteArray = xml.getBytes();
ByteArrayOutputStream out = new ByteArrayOutputStream(byteArray.length);
formatter.save(out, options);
return out.toString();
} catch (IOException e) {
System.err.println("IOException while creating ByteArrayOutputStream for formatting xml.", e);
}
}
[Click to add or edit comments])
Please prepend comments below including a date