Format XML output with apache commons configuration XMLConfiguration

筅森魡賤 提交于 2019-12-07 03:10:18

问题


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?


回答1:


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



回答2:


You can refer to this threads, which provides a lot of simple way to deal with xml format in Java.



来源:https://stackoverflow.com/questions/5761610/format-xml-output-with-apache-commons-configuration-xmlconfiguration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!