【问题标题】:Format XML output/modify Transformer in apache commons-configurations2在 apache commons-configurations2 中格式化 XML 输出/修改 Transformer
【发布时间】:2017-10-11 12:09:16
【问题描述】:

我正在尝试从旧的 commons-configuration 迁移到 commons-configuration2,但是在使用新的 Configurations 构建器时,我无法使用缩进格式化 XML 输出。

在我这样做之前,效果很好。

XMLConfiguration configuration = new XMLConfiguration()
{
    @Override
    protected Transformer createTransformer()
        throws ConfigurationException
    {
        Transformer transformer = super.createTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("http://xml.apache.org/xslt}indent-amount", "4");
        return transformer;
    }
};

但在 commons-configurations2 中,您使用 ConfigurationBuilder 来获取 XMLConfiguration 实例,这消除了创建 XMLConfiguration 子类的能力,例如:

XMLConfiguration configuration = configurations
        .xmlBuilder(new File("config.xml"))
        .getConfiguration();

还有其他方法可以自定义 XMLConfiguration 的 Transformer 吗?

谢谢!

【问题讨论】:

    标签: java xml apache-commons-config


    【解决方案1】:

    这是我解决它的方法。

    创建一个扩展 XMLConfiguration 的新类:

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

    像这样创建 XMLConfiguration:

    XMLConfiguration builder = new Configurations()
            .fileBasedBuilder(PrettyXMLConfiguration.class, new File("config.xml"))
            .getConfiguration();
    

    甚至更简单:

    XMLConfiguration builder = new Configurations()
        .fileBased(PrettyXMLConfiguration.class, new File("config.xml"));
    

    【讨论】:

      猜你喜欢
      • 2011-08-11
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多