scala – Play框架:将XML解析为模型

我在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,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,因为我想让程序看起来更简单.解析日期非常简单,足以阅读Joda Time library documentation.

相关文章

共收录Twitter的14款开源软件,第1页Twitter的Emoji表情 Tw...
Java和Scala中关于==的区别Java:==比较两个变量本身的值,即...
本篇内容主要讲解“Scala怎么使用”,感兴趣的朋友不妨来看看...
这篇文章主要介绍“Scala是一种什么语言”,在日常操作中,相...
这篇文章主要介绍“Scala Trait怎么使用”,在日常操作中,相...
这篇文章主要介绍“Scala类型检查与模式匹配怎么使用”,在日...