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

Mat*_*tRS 6 java xml-serialization apache-commons-config

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

<root>
<node>
<child>
</child>
</node>
</root>
Run Code Online (Sandbox Code Playgroud)

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

小智 10

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)