我用:
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);
答案 0 :(得分:2)
如果原始输入XML本身缩进,则输出器添加的缩进将看起来不正确。在重新缩进之前,您可以尝试使用简单的XSLT去除原始XML中的任何缩进,而不是无操作标识转换器:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Source xsltSource = new StreamSource(new StringReader(
"<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'\n"
+ " xmlns:xalan='http://xml.apache.org/xalan'>\n"
+ " <xsl:strip-space elements='*' />\n"
+ " <xsl:output method='xml' indent='yes' xalan:indent-amount='4' />\n"
+ " <xsl:template match='/'><xsl:copy-of select='node()' /></xsl:template>\n"
+ "</xsl:stylesheet>"
));
Transformer transformer = transformerFactory.newTransformer(xsltSource);
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("output.xml"));
transformer.transform(source, result);