我有一些使用嵌入式 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/