6

I am using the apache commons configuration XMLConfiguration to build and save an XML file. When saving there is no formatting. I get something like:

<root>
<node>
<child>
</child>
</node>
</root>

I know there are plenty of ways to use some other library to take that output and format it, but surely there must be a way to set something as simple as indention from commons configuration?

Emmanuel Bourg
  • 9,601
  • 3
  • 48
  • 76
MattRS
  • 428
  • 5
  • 8

1 Answers1

10

Encountered the same issue. Although the question was asked long time ago, would like to share a solution :

XMLConfiguration class has a protected method called createTransformed. It should be extended and set by right configuration for indentation.

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;
    }
}
Community
  • 1
  • 1
Ozgun Alan
  • 310
  • 3
  • 9
  • You don't need the constructor. The createTransformer in XMLConfiguration sets the Indent to "yes" but the indent-amount was missing. – ezzadeen Dec 01 '17 at 04:24