Reputation: 628
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)
)
Upvotes: 6
Views: 2539
Reputation: 6805
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.
Upvotes: 4
Reputation: 11479
The form mapping does not do XML parsing, only form parsing, you will have to use the Scala XML support (or some library of your preference). Search the interwebs and you will find a multitude of examples of how to use it.
Upvotes: 0