Last active
August 29, 2015 14:23
-
-
Save kkismd/87e073fadfa63423308a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Example { | |
import scala.xml._ | |
import scala.util.control.Exception._ | |
def str(node: Node, key: String): Option[String] = (node \\ key).headOption.map(_.text) | |
def int(node: Node, key: String): Option[Int] = allCatch opt { str(node, key).map(_.toInt).get } | |
case class Person(name: String, age: Int) | |
def main (args: Array[String]) { | |
val xml = | |
<people> | |
<person> | |
<name>Taro Hara</name> | |
<age>14</age> | |
</person> | |
<person> | |
<name>Yoko Yamada</name> | |
<age>15</age> | |
</person> | |
</people> | |
val people = (xml \\ "person") flatMap { node => | |
for { | |
name <- str(node, "name") | |
age <- int(node, "age") | |
} yield Person(name, age) | |
} | |
println(people) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment