如何在 Scala Class 中漂亮地表示 XML 实体?

How to represent an XML entity in a Scala Class beautifully?

虽然这个问题可能会在其他编程语言中得到解答,但我觉得 Scala 中缺少它。

我想在 Scala class 中使用代表以下示例 XML 的清晰 DSL,以便我可以在我的 XML over REST 中轻松使用它(播放) 框架。

<?xml version="1.0" encoding="UTF-8">
<requests>
  <request type="foo" id="1234">
    <recipient>bar<recipient>
    <recipient>baz<recipient>
    <body>This is an example string body</body>
    <ext>Optional tag here like attachments</ext>
    <ext>Optional too</ext>
  </request>
</requests>

这是我在 Scala 中表示上述模型的尝试 class:

class Attribute[G](
  value:G
)

class Request(
  type: Attribute[String],
  id: Attribute[Integer],
  recipient[List[String]],
  body: String,
  ext: Option[List[String]] // Some or None
)

// how it's used
val requests = List[Request]

这不是作业,我正在尝试编写一个正在运行的应用程序,以将公司内部 REST 转换为行业标准。 (如果有人好奇,那就是 OpenCable ESNI vI02 XML 格式)

我的问题:我是否正确表示了 "foo" 和 "id" 属性?如果是这样,我将如何轻松输出 XML 而无需太多按摩或粗略的字符串插值。我希望 foo 和 id 被解释为属性而不是像这样的嵌套标签:

...<request><type>foo</type><id>1234</id>...DO NOT WANT

谢谢!

XML 标签是 Scala 中的第一个 class 公民,使您能够以比其他语言更简洁的方式使用标签。

从 Scala 2.11 开始,XML 库已提取到 its own package

有了它,您可以轻松地使用一些惯用的 Scala 来实现您的目标:

case class Request(requestType: String, id: Int, recipients: List[String], body: String, ext: Option[List[String]]){

      def toXML =
        <requests>
          <request type={requestType} id={id}>
              {recipientsXML}
              <body>{body}</body>
              {extXML}
          </request>
        </requests>

      private def recipientsXML = 
        recipients.map(rec => <recipient>{rec}</recipient>)
      private def extXML = for {
        exts <- ext
        elem <- exts
      } yield <ext>{elem}</ext>
}