使用apache commons配置XMLConfiguration格式化XML输出

我正在使用apache commons配置XMLConfiguration来构建和保存XML文件。 保存时没有格式化。 我有类似的东西:

      

我知道有很多方法可以使用其他库来获取输出并对其进行格式化,但是肯定必须有一种方法来设置像公共配置中的缩进一样简单的东西吗?

遇到了同样的问题。 虽然很久以前就提出了这个问题,但想分享一个解决方案:

XMLConfiguration类有一个名为createTransformed的受保护方法。 它应该通过正确的配置进行扩展和设置以进行缩进。

 public class ExtendedXMLConfiguration extends XMLConfiguration { public ExtendedXMLConfiguration(File file) throws ConfigurationException { super(file); } @Override protected Transformer createTransformer() throws TransformerException { Transformer transformer = super.createTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); return transformer; } } 

您可以参考这个线程 ,它提供了很多简单的方法来处理Java中的xml格式。