就我个人而言,我喜欢使用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的sytle语法,这将工作:
val myBool = (xml \ "bool_node").text.toBoolean
或者,你可以混合和匹配他们为y ou看起来合适 - 模式匹配和XPath语法都是可组合和互操作的。
可能的诱惑http://stackoverflow.com/questions/1470230/scala-elegant-conversion-of-a-string-into-a-boolean – 2013-04-04 17:26:12
@alexwriteshere谢谢,我已经看到了这个问题, m知道'toBoolean'方法。如果XML需要一些特殊处理,或者有一些最佳实践(如验证),那么只是漫游。 – Haspemulator 2013-04-04 17:33:09