public String filter(String message) {
if (message == null) {
return null;
}
// Remove formatting, transformer fails to handle wrong indentation correctly.
message = message.replaceAll(">\\s*[\\r\\n]+\\s*", ">");
message = message.replaceAll("\\s*[\\r\\n]+\\s*", " "); // for wrapped attribute lists
Source xmlInput = new StreamSource(new StringReader(message));
StringWriter stringWriter = new StringWriter();
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", INDENT); // for Java 6
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", INDENT.toString()); // Java 1.5
transformer.transform(xmlInput, new StreamResult(stringWriter));
String pretty = stringWriter.toString();
pretty = pretty.replace("\r\n", "\n");
return pretty;
} catch (TransformerException e) {
if (e.getCause() != null && e.getCause() instanceof SAXParseException) {
return message;
}
throw new RuntimeException(e);
}
}
but i get exception here:
transformerFactory.setAttribute("indent-number", INDENT); // for Java 6
java.lang.IllegalArgumentException: Not supported: indent-number
my java:
java version "1.6.0_33"
why i get this error?
I fixed that exception by commenting this line:
transformerFactory.setAttribute("indent-number", indent);
and adding this line:
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
The exception is gone even though the indetation that appears in the browser is incorrect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With