【问题标题】:Generating formatted XML in Scala在 Scala 中生成格式化的 XML
【发布时间】:2013-06-10 10:06:32
【问题描述】:

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

【问题讨论】:

标签: xml scala formatting


【解决方案1】:

使用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 计算结果为 &lt;/a&gt; 怎么办?)

【讨论】:

  • 是否有替代PrettyPrint 以XML 形式返回的Node 而不是String?我希望能够直接print 格式化节点而不首先使用prettyprinter。现在我正在构建节点,漂亮的打印,然后解析回一个节点 XML.loadString(prettyPrinter format xml) 似乎效率不高。
  • @tsjnsn 我明白你的意思。显然XML.loadString 保留了不重要的空白。这不是 XML 解析器所必需的行为(请参阅 w3.org/TR/xml/#sec-white-space),除非在文档本身中指定(因此将来可能会更改)。我建议您仅在实际需要 String 时才使用 PrettyPrinter
猜你喜欢
  • 2011-03-22
  • 2012-02-15
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
相关资源
最近更新 更多