我用:
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个空格(如果可能的话用一个制表符)来标识节点吗?
源代码:
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);发布于 2013-11-06 17:29:19
如果原始输入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);https://stackoverflow.com/questions/19808441
复制相似问题