我正在使用apache commons配置XMLConfiguration来构建和保存XML文件。 保存时没有格式。 我得到的是这样的:使用apache commons配置格式化XML输出XMLConfiguration
<root>
<node>
<child>
</child>
</node>
</root>
我知道有很多方法可以使用一些其他的库采取的是输出和格式化,但肯定必须有设置为从公共配置缩进一样简单的方式?
我正在使用apache commons配置XMLConfiguration来构建和保存XML文件。 保存时没有格式。 我得到的是这样的:使用apache commons配置格式化XML输出XMLConfiguration
<root>
<node>
<child>
</child>
</node>
</root>
我知道有很多方法可以使用一些其他的库采取的是输出和格式化,但肯定必须有设置为从公共配置缩进一样简单的方式?
你可以参考this threads,它提供了很多简单的方法来处理Java中的xml格式。
遇到同样的问题。尽管很久以前提出了这个问题,但想分享一个解决方案:
XMLConfiguration类具有一个名为createTransformed的受保护方法。它应该被扩展并由right configuration设置缩进。
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;
}
}
你不需要构造函数。 XMLConfiguration中的createTransformer将缩进设置为“是”,但缩进量丢失。 – ezzadeen 2017-12-01 04:24:15
我在发布之前就看到了。正如我所说的,我知道如何在许多其他库中格式化XML,但是我的代码已经在使用apaches常用配置,并且我不想使用2个不同的XML库。 – MattRS 2011-04-24 04:18:40
是的,在那个线程中,有人提供了一种方法,通过标准Java库(这不是另一个XML库)将其另存为格式化的xml文件。因为apache-commons似乎没有提供输出格式化xml文件的方法。 – jumperchen 2011-04-24 07:04:06