如何在 Scala 中生成格式良好的 XML? [英] How to produce nicely formatted XML in Scala?

查看:58
本文介绍了如何在 Scala 中生成格式良好的 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您定义了以下内容:

Say you define the following:

class Person(name: String, age: Int) {
    def toXml =
        <person>
            <name>{ name }</name>
            <age>{ age }</age>
        </person>   
}

val Persons = List(new Person("John", 34), new Person("Bob", 45))

然后生成一些 XML 并将其保存到文件中:

Then generate some XML and save it to a file:

val personsXml = 
    <persons>
        { persons.map(_.toXml) }
    </persons>

scala.xml.XML.save("persons.xml", personsXml)

您最终会得到以下看起来很有趣的文字:

You end up with the following funny-looking text:

<persons>
        <person>
            <name>John</name>
            <age>32</age>
        </person><person>
            <name>Bob</name>
            <age>43</age>
        </person>
    </persons>

现在,当然,这是完全有效的 XML,但是如果您希望它可以在合适的文本编辑器中进行人工编辑,则最好将其格式化得更好一点.

Now, of course, this is perfectly valid XML, but if you want it to be human-editable in a decent text editor, it would be preferable to have it formatted a little more nicely.

通过更改 Scala XML 文字的各个点的缩进 - 使代码看起来 - 可以生成上述输出的变体,但似乎不可能完全正确.我理解为什么它会变成这种格式,但想知道是否有任何方法可以解决它.

By changing indentation on various points of the Scala XML literals - making the code look less nice - it's possible to generate variations of the above output, but it seems impossible to get it quite right. I understand why it becomes formatted this way, but wonder if there are any ways to work around it.

推荐答案

您可以使用 scala.xml.PrettyPrinter 对其进行格式化.遗憾的是,这不适用于大型文档,因为它仅格式化为 StringBuilder 而不会直接写入流或写入器.

You can use scala.xml.PrettyPrinter to format it. Sadly this does not work for large documents as it only formats into a StringBuilder and does not write directly into a stream or writer.

这篇关于如何在 Scala 中生成格式良好的 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆