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



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

我想使用一个清晰的DSL,在Scala类中表示以下示例XML,以便我可以轻松地在我的XML over REST (play)框架中使用它。

<?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 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"one_answers"id"属性?如果是这样,我如何轻松地输出XML,而不需要太多的修改或粗糙的字符串插值。我希望foo和id被解释为属性,而不是像这样的嵌套标签:

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

谢谢!

XML标记是Scala中的一等公民,使您能够以比其他语言更干净的方式使用标记。

从Scala 2.11开始,XML库已经被提取到它自己的包中。

有了这些,您就可以轻松地使用一些惯用的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>
}

最新更新