I use:
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
From this question Java: How to Indent XML Generated by Transformer , but as someone says: it doesn't ident the inner nodes as we expect to (it does ident them but not with 4 spaces).
So it's 4 spaces for first level of identation and 2 spaces for the next level like:
<a>
<b>
<b_sub></b_sub>
</b>
<c></c>
</a>
Numbering the spaces:
<a>
(4)<b>
(2)<b_sub></b_sub>
(4)</b>
(4)<c></c>
(2)</a>
Can we ident nodes with 4 spaces (or with 1 tab if possible?)?
Source code:
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
NodeList rootlist = doc.getElementsByTagName("root_node"); //(example name)
Node root = rootlist.item(0);
root.appendChild(...);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("output.xml"));
transformer.transform(source, result);