我正在使用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