MattRS
MattRS

Reputation: 428

Format XML output with apache commons configuration XMLConfiguration

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?

Upvotes: 6

Views: 5088

Answers (1)

Ozgun Alan
Ozgun Alan

Reputation: 320

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

Upvotes: 10

Related Questions