我用:
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
从这个问题Java: How to Indent XML Generated by Transformer 开始,但正如有人所说:它没有像我们期望的那样识别内部节点(它确实识别它们,但没有 4 个空格)。
因此,第一级标识有 4 个空格,下一级有 2 个空格,例如:
<a>
<b>
<b_sub></b_sub>
</b>
<c></c>
</a>
给空格编号:
<a>
(4)<b>
(2)<b_sub></b_sub>
(4)</b>
(4)<c></c>
(2)</a>
我们可以用 4 个空格(或者如果可能的话用 1 个制表符)来识别节点吗?
源代码:
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);