2013-10-08 4 views
5

Ich habe einfache Entität in Webapp von Play Framework gesteuert. Es sieht wie folgt aus:Play Framework: Pars XML zu Modell

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

Und ich bekomme die XML-Daten aus DB, der wie folgt aussieht:

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

Und jetzt habe ich keine Ahnung, mit ihm zum Modell und Form-Mapping-Parsing.

Meine Form Mapping für alle Fälle (nicht kompiliert jetzt):

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

Antwort

3

Hier ist der Beispielcode für den ersten Teil der Frage ist:

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) 

} 

Und das Ergebnis von 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))) 

nahm ich die Freiheit, die commentDate-String zu ändern, wie ich wollte um das Programm einfacher aussehen zu lassen. Das Analysieren der Date ist ziemlich einfach und es ist genug, die Joda Time library documentation.

zu lesen
0

Die Form Zuordnung nicht das Parsen von XML macht, nur Form Parsing, werden Sie die Scala XML-Unterstützung verwenden müssen (oder einige Bibliothek Ihrer Wahl). Durchsuchen Sie die Interwebs und Sie finden eine Vielzahl von Beispielen für die Verwendung.