Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play framework: parse XML to model

I have simple entity in webapp driven by Play framework. It looks like this:

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

And I get the XML from DB that looks like this:

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

And now I have no idea with parsing it to the model and form mapping.

My form mapping just in case (doesn't compile now):

  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)
  )
like image 806
vicont Avatar asked Oct 08 '13 07:10

vicont


1 Answers

Here is the sample code for the first part of the question:

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)

}

And the result from 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)))

I took the freedom to change the commentDate to String as I wanted to make the program look simpler. Parsing the Date is quite simple and it's enough to read the Joda Time library documentation.

like image 189
Rajish Avatar answered Oct 26 '22 08:10

Rajish