xml - 在 Scala 中生成格式化的 XML

我有一些使用嵌入式 Scala 生成的 XML,但它没有将生成的 XML 放在单独的行中。

目前是这样的,

<book id="0">
      <author>Gambardella, Matthew</author><publish_date>Sun Oct 01 00:00:00 EDT 2000</publish_date><description>An in-depth loo
k at creating applications with XML.</description><price>44.95</price><genre>Computer</genre><title>XML Developer's Guide</title>
    </book>

但我希望它看起来像这样:

<book id="0">
  <author>Gambardella, Matthew</author>
  <publish_date>Sun Oct 01 00:00:00 EDT 2000</publish_date>
  <description>An in-depth look at creating applications with XML.</description>
  <price>44.95</price>
  <genre>Computer</genre>
  <title>XML Developer's Guide</title>
</book>

如何控制格式? 这是生成 XML 的代码

<book id="0">
  { keys map (_.toXML) }
</book>

这里是 toXML:

def toXML:Node = XML.loadString(String.format("<%s>%s</%s>", tag, value.toString, tag))

最佳答案

使用 PrettyPrinter :

val xml = // your XML

// max width: 80 chars
// indent:     2 spaces
val printer = new scala.xml.PrettyPrinter(80, 2)

printer.format(xml)

顺便说一句,您可能需要考虑更换您的 toXML与:

def toXML: Node = Elem(null, tag, Null, TopScope, Text(value.toString))

这可能更快,并且消除了所有类型的转义问题。 (如果 value.toString 的计算结果为 </a> 怎么办?)

https://stackoverflow.com/questions/17096938/

相关文章:

java - 无法解析自定义日期格式。 ( java )

python - 带有负索引的 str.format(list) 在 Python 中不起作用

php - mysql时间戳转换/格式化通知: A non well formed numeric

python - 格式化数字,使它们在小数点上对齐

iphone - 在Objective-C中将小数转换为分数?

java - RSS 2.0 提要中的 RFC-822 日期时间格式 : CET not accep

perl - 在 Perl 中获取 UTC 偏移量的最佳方法是什么?

git - 如何为 git diff 中使用的寻呼机设置标签大小?

formatting - 如何打印具有所有可用精度的 Rust float ?

git - Git 提交消息的推荐格式