使用Transformer缩进XML文本

我正在编写一个包含以下代码的XML文件:

Source source = new DOMSource(rootElement); Result result = new StreamResult(xmlFile); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(source, result); 

这是输出文件:

    0   274.0 316.0  ... 

我希望这个文件缩进,例如:

    0   274.0 316.0  ... 

在我的代码中调用setOutputProperty并没有解决问题,它实际上使文本用新行(但不缩进)。

任何人都有这个解决方案,而不需要外部库?

您可能还必须指定缩进的空格量:

 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");