scala - Play Framework : parse XML to model

标签 scala xml-parsing playframework-2.0

我在由 Play 框架驱动的 webapp 中有简单的实体。它看起来像这样:

case class MyItem(id: Option[Long] = None, name: String, comments: List[Comment])
case class Comment(commentDate: Date, commentText: String)

我从 DB 得到的 XML 如下所示:
<?xml version="1.0"?>
<item>
    <id>1</id>
    <name>real item</name>
    <comments> 
        <comment>
            <comment_date>01.01.1970</comment_date>
            <comment_text>it rocks</comment_text>
        </comment>
        <comment>
            <comment_date>02.01.1970</comment_date>
            <comment_text>it's terrible</comment_text>
        </comment>      
    </comments>
</item>

现在我不知道将它解析为模型和表单映射。

我的表单映射以防万一(现在不编译):
  val itemForm = Form(
    mapping(
      "id" -> optional(longNumber),
      "name" -> nonEmptyText,
      "comments" -> list(mapping(
          "commentDate" -> date("dd.mm.yyyy"),
          "commentText" -> text
      )(Comment.apply)(Comment.unapply))
    )(MyItem.apply)(MyItem.unapply)
  )

最佳答案

这是问题第一部分的示例代码:

import scala.xml.{Comment => _, _}


case class Comment(commentDate: String, commentText: String)
case class MyItem(id: Option[Long] = None, name: String, comments: List[Comment])

object MyParser {
  def parse(el: Elem) =
    MyItem(Some((el \ "id").text.toLong), (el \ "name").text,
      (el \\ "comment") map { c => Comment((c \ "comment_date").text, (c \ "comment_text").text)} toList)

}

REPL 的结果:
scala> MyParser.parse(xml)
MyParser.parse(xml)
res1: MyItem = MyItem(Some(1),real item,List(Comment(01.01.1970,it rocks), Comment(02.01.1970,it's terrible)))

我拿了改commentDate的自由至 String因为我想让程序看起来更简单。解析 Date非常简单,阅读 Joda Time library documentation. 就足够了

关于scala - Play Framework : parse XML to model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19241930/

相关文章:

clojure - 补充 clojure-xml/parse 的可用 Clojure XML 解析库

templates - 是否可以覆盖表单助手?

java - Play框架打包源文件

scala - 什么是投影仪

scala - Play Framework 中指定的基础 docker 镜像在哪里?

scala - Play 2.3 FakeApplication 模式没有在测试中设置?

java - XML属性解析

python - 在 python 中解析 XML 文件以用于发送电子邮件

forms - 如何在 scala/lift 中创建一个简单的 Web 表单

scala - Play Framework-开发服务器在刷新后关闭