2013-10-08 1 views
5

私は、Playフレームワークによって駆動されるwebapp内に単純なエンティティを持っています。Play framework:モデル化する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))) 

私が望んでいたように私はStringcommentDateを変更するために自由を取りましたプログラムをよりシンプルに見せることができます。 Dateの解析は非常に簡単で、それを読むだけで十分です。Joda Time library documentation.

0
XML解析を行いませんフォームのマッピングは、形だけの解析は、あなたがScalaのXMLサポートを使用する必要があります

(またはいくつかあなたの好みのライブラリ)。 interwebsを検索すると、それを使用する方法の例の多数を見つけるでしょう。ここで

関連する問題