【问题标题】:Format XML output with apache commons configuration XMLConfiguration使用 apache commons 配置 XMLConfiguration 格式化 XML 输出
【发布时间】:2011-08-11 07:43:39
【问题描述】:

我正在使用 apache commons 配置 XMLConfiguration 来构建和保存 XML 文件。 保存时没有格式化。 我得到类似的东西:

<root>
<node>
<child>
</child>
</node>
</root>

我知道有很多方法可以使用其他库来获取该输出并对其进行格式化,但肯定有一种方法可以设置像从公共配置中缩进这样简单的东西吗?

【问题讨论】:

    标签: java xml-serialization apache-commons-config


    【解决方案1】:

    遇到了同样的问题。虽然这个问题是很久以前提出的,但想分享一个解决方案:

    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 将 Indent 设置为“yes”,但缺少 indent-amount。
    【解决方案2】:

    你可以参考this threads,它提供了很多简单的方法来处理Java中的xml格式。

    【讨论】:

    • 我在发帖之前就看到了。正如我所说,我知道如何在许多其他库中格式化 XML,但我的代码已经在使用 apaches 通用配置,我不想使用 2 个不同的 XML 库。
    • 是的,在那个线程中,有人提供了一种通过标准 Java 库保存为格式化 xml 文件的方法,该库不是另一个 XML 库。因为 apache-commons 似乎没有提供输出格式化 xml 文件的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多