2017-10-11 106 views
1

我想从旧公共配置迁移到公用配置2,但我在使用新的配置生成器时格式化XML输出的缩进问题。格式XML输出/修改变压器在Apache公用 - 配置2

在我这样做之前,哪些工作正常。

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

但在公地configurations2您使用ConfigurationBuilder获得XMLConfiguration中的实例,它删除了创建XMLConfiguration中的一个子类的能力,比如像这样:

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

是否有任何其他方式定制XMLConfiguration的变压器?

谢谢!

回答

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"));