如何将布尔值从XML提取到Scala case类
我刚开始学习Scala,所以请接受我的新手问题。:)我正在探索Scala中XML支持的强大功能,并完成了一项任务:我有一个XML文档,其中一个节点包含一个类似布尔值:如何将布尔值从XML提取到Scala case类,scala,xml-parsing,playframework-2.0,Scala,Xml Parsing,Playframework 2.0,我刚开始学习Scala,所以请接受我的新手问题。:)我正在探索Scala中XML支持的强大功能,并完成了一项任务:我有一个XML文档,其中一个节点包含一个类似布尔值:true。我还有一个case类,里面有一个布尔字段。我想要实现的是从XML创建该类的实例 显然,问题在于XML的只包含一个字符串,而不是布尔值。处理这种情况的最佳方法是什么?只需尝试使用myString.toBoolean将该字符串转换为布尔值即可?或者其他方法可能更好 提前谢谢 就个人而言,我喜欢对XML使用模式匹配 最简单的方法
true
。我还有一个case类,里面有一个布尔字段。我想要实现的是从XML创建该类的实例
显然,问题在于XML的
只包含一个字符串,而不是布尔值。处理这种情况的最佳方法是什么?只需尝试使用myString.toBoolean
将该字符串转换为布尔值即可?或者其他方法可能更好
提前谢谢 就个人而言,我喜欢对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
或者,您可以根据需要混合和匹配它们-模式匹配和XPath语法都是可组合和可互操作的。可能是@AlexWriteShare的重复。谢谢,我已经看到了这个问题,并且我知道
toBoolean
方法。只是想知道XML是否需要特殊处理,或者是否有一些最佳实践,比如验证。谢谢您的回答,它提供了信息。我不接受它,因为带有公认答案的StackOverflow问题往往会被社区忽略,我仍然希望有人能提供更多信息,或者其他例子,或者至少给出这个答案+1,以表明它是完整的,没有任何内容可以添加。
// 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
val myBool = (xml \ "bool_node").text.toBoolean