2017-10-11 105 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"));