2013-10-08 49 views
5

我在Play框架驅動的webapp中有簡單的實體。它看起來像這樣:玩框架:解析XML到模型

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) 
) 

回答

3

下面是問題的第一部分的示例代碼:

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.

0

形式映射沒有做XML解析,唯一形式解析,你將不得不使用Scala的XML支持(或一些您偏好的圖書館)。搜索interwebs,你會發現很多關於如何使用它的例子。