1

I am trying to migrate from the old commons-configuration to commons-configuration2 but I am having trouble formatting the XML output with indentation when using the new Configurations builder.

Before I did like this, which worked fine.

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

But in commons-configurations2 you use a ConfigurationBuilder to get a XMLConfiguration instance, which removes the ability to create a subclass of XMLConfiguration, for example like this:

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

Is there any other way of customizing the XMLConfiguration's Transformer?

Thanks!

langen
  • 740
  • 5
  • 17

1 Answers1

2

Here is how I solved it.

Create a new class which extends 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;
    }
}

Create the XMLConfiguration like this instead:

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

or even simpler:

XMLConfiguration builder = new Configurations()
    .fileBased(PrettyXMLConfiguration.class, new File("config.xml"));
langen
  • 740
  • 5
  • 17