Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 523
MattRS Avatar asked Apr 23 '11 01:04

MattRS


1 Answers

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;
    }
}
like image 156
Ozgun Alan Avatar answered Sep 25 '22 02:09

Ozgun Alan