Scala – retrieve data from XML
Filed in Coding, 22/01/2010, 13:49 by parheliumI started learning Scala 2 months ago, because Groovy’s performance was too low for my purpose -> modelling epidemies on cellular automata.
Appeared a need to throw variables – important for epidemy simulation – to external file.
Scala provides simple interface to use XML data.
Below you can find examples how to retrieve data from XML.
It’s very convenient to work with Scala through console:
scala> x res5: scala.xml.Elem =0.01 0.4 0.5 0.7
Get “init” node in 2 ways:
scala> x \\ "init" res15: scala.xml.NodeSeq =0.01 scala> x \ "init" res16: scala.xml.NodeSeq =0.01
Get “individual” node in 2 ways:
scala> x \\ "individual" res17: scala.xml.NodeSeq =0.7 scala> x \ "die" \ "individual" res23: scala.xml.NodeSeq =0.7
Conclusion:
- “\” is used to search through first level of node’s children
- “\\” is used to search through every level od node’s children.
Get “init” value :
scala> (x \ "init").text res19: String = 0.01 scala> (x \ "init").text.toDouble res20: Double = 0.01
Get “individual” value:
scala> (x \ "die" \ "individual").text res22: String = 0.7
Similarly you can get attribute:
scala> x \ "recover" \ "@tip" res28: scala.xml.NodeSeq = const|individual scala> (x \ "recover" \ "@tip").text res29: String = const|individual
If you would like to react on specific value in attribute use:
scala> (x \ "recover" \ "@src").text match{
case "const" => true;
case "individual" => false;
case _ => false;
}
res31: Boolean = true