本文介绍了使用 apache commons 配置 XMLConfiguration 格式化 XML 输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 apache 公共配置 XMLConfiguration 来构建和保存 XML 文件.保存时没有格式.我得到类似的信息:

I am using the apache commons configuration XMLConfiguration to build and save an XML file.When saving there is no formatting.I get something like:

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

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

I know there are plenty of ways to use some other library to take that output and format it, but surely there must be a way to set something as simple as indention from commons configuration?

推荐答案

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

Encountered the same issue. Although the question was asked long time ago, would like to share a solution :

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

XMLConfiguration class has a protected method called createTransformed. It should be extended and set by right configuration for indentation.

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;
    }
}

这篇关于使用 apache commons 配置 XMLConfiguration 格式化 XML 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 06:12