使用Apache Commons Configuration XMLConfiguration格式化XML输出

6
我正在使用apache commons configuration XMLConfiguration来构建和保存XML文件。在保存时,没有进行格式化处理。我得到了类似于以下的内容:
<root>
<node>
<child>
</child>
</node>
</root>

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

1个回答

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

你不需要构造函数。 XMLConfiguration中的createTransformer将Indent设置为“是”,但缺少缩进量。 - ezzadeen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接