I’ve tried
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
XMLReader reader = factory.newSAXParser().getXMLReader();
Source xmlInput = new SAXSource(reader, new InputSource(new StringReader(xml)));
StringWriter stringWriter = new StringWriter();
xmlPretty = new StreamResult(stringWriter);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlPretty);
return xmlPretty.getWriter().toString();
but as soon as there is an “ignorable space” the indentation stops. I’ve searched a lot but found nothing about ignorable spaces in sax parsers, except in Handlers. So I’ve tried to add a handler of mine:
class MyHandler extends DefaultHandler {
@Override
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
System.out.println("foo");
}
}
...
reader.setContentHandler(new MyHandler());
but it never prints “foo”.
Update:
Here is an example of input:
<n:a> <b>foo </b> </n:a>
So well-formed but invalid (n is not defined). I want the function to output something like:
<n:a>
<b>foo </b>
</n:a>
The program above does output this if I provide it with:
<n:a><b>foo </b></n:a>
But not with <n:a> <b>foo </b> </n:a>.
I don’t think the namespace not declared makes any difference, while additional whitespaces do.
I tried your code and, I’m still trying to understand why, if you add this line
you should have the desired output. Could you confirm this and check for any eventual side effects?