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

2024-02-18

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

<root>
<node>
<child>
</child>
</node>
</root>

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


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

XMLConfiguration 类有一个名为 createTransformed 的受保护方法。它应该被扩展和设置正确的配置 https://stackoverflow.com/questions/1384802/java-how-to-indent-xml-generated-by-transformer用于缩进。

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;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 apache commons 配置 XMLConfiguration 格式化 XML 输出 的相关文章

随机推荐