0

I've just started with Scala, so please bear with my newbie question. :) I'm exploring the wonderful powers of XML support in Scala, and came to a task: I have an XML document with a node containing a boolean-like value: <bool_node>true</bool_node>. I also have a case class with a boolean field in it. What I want to achieve is to create an instance of that class from the XML.

The problem, obviously, is that for XML <bool_node> contains just a string, not boolean. What is the best way to handle this situation? Just try to convert that string to boolean using myString.toBoolean? Or some other approach could is better?

Thanks in advance!

4

1 回答 1

2

就个人而言,我喜欢对 XML 使用模式匹配。

最简单的方法是这样的:

// This would have come from somewhere else
val sourceData = <root><bool_node>true</bool_node></root>

// Notice the XML on the left hand side. This is because the left hand side is a
// pattern, for pattern matching.
// This will set stringBool to "true"
val <root><bool_node>{stringBool}</bool_node><root> = sourceData

// stringBool is a String, so must be converted to a Boolean before use
val myBool = stringBool.toBoolean

如果这种情况经常发生,另一种可能有意义的方法是定义您自己的提取器:

// This only has to be defined once
import scala.xml.{NodeSeq, Text}
object Bool {
  def unapply(node: NodeSeq) = node match {
    case Text("true") => Some(true)
    case Text("false") => Some(false)
    case _ => None
  }
}

// Again, notice the XML on the left hand side. This will set myBool to true.
// myBool is already a Boolean, so no further conversion is necessary
val <root><bool_node>{Bool(myBool)}</bool_node></root> = sourceData

或者,如果您使用 XPath 样式语法,这将起作用:

val myBool = (xml \ "bool_node").text.toBoolean

或者,您可以根据需要混合和匹配它们 - 模式匹配和 XPath 语法都是可组合和可互操作的。

于 2013-04-10T10:01:16.020 回答