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)
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With