1

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.

4

1 回答 1

2

您的代码的一个问题是,在转换后无法判断该double值是丢失还是存在但设置为0.0.

首先想到的是 scalas Option。您的案例类如下所示:

case class Content(name:String, description:String, someDouble: Option[Double])

转换将是:

implicit def NodeSeqToDouble(value: NodeSeq) = {
  value.text match {
    case "" => None
    case s:String => Some(s.toDouble)
  }
}

这意味着在转换之后double仍然保留存在或缺失的信息。

于 2013-04-19T07:53:33.043 回答