I'm looking for a better way of building objects from XML in Scala, similar to what's happening in this SO question. I'd like to read xml which may contain missing elements. Currently, I'm using a case class:
case class Content(name:String, description:String, someDouble: Double)
When reading xml, I'm passing in a Node to the following function:
def buildContent(node: Node) = {
Content((node \ "name").text,
(node \ "description").text,
(node \ "someDouble")
}
My problem is that "someDouble" may or may not be present in the current XML snippet, which would be fine if this was a string but I need to treat it as a double. Currently I'm handling this with an implicit conversion
implicit def NodeSeqToDouble(value: NodeSeq) = {
value.text match {
case "" => 0.0
case s:String => s.toDouble
}
}
Which works, but seems verbose and somewhat ugly. I'm wondering if there is a "best practices" way of dealing with optional elements when a type conversion is involved on an optional xml element.