Scala原生支持xml,就如同Java支持String一样,这就让生成xml和xhtml很简单优雅:
val name = "james"
val age = 10
val html = name={name}, age="{age}" toString
// name=james, age="10"
又如:
val html =
更复杂的例子:
val x =
//
val x0 =
val
By the way, if you want to include a curly brace (`{' or `}') as XML text, as opposed to using them to escape to Scala code, simply write two curly braces in a row:
scala> {{{{brace yourself!}}}} res1: scala.xml.Elem = {{brace yourself!}}
xml.XML loadString ""
xml.XML loadFile "abc.xml"
xml.XML.saveFull("foo.xml", node, "UTF-8", xmlDecl: Boolean, doctype : DocType)
val x =
//
(x \ "e") map (_.text.toInt) // List(1, 2, 3, 4, 5)
val x0 =
(x0 \ "user") //
(x0 \ "user" \ "age") // (
(x0 \ "age") // 直接下级: ()
(x0 \\ "age") // 所有下级:(
(x0 \ "_") 所有
val x =
scala> (x \ "u" \\ "@name") foreach println
qh
james
qiu
例子:
val data =
val res = for (item <- data \ "item" ;
price = (item \ "@price").text.toDouble ;
qty = (item \ "@quantity").text.toInt)
yield (price * qty)
printf("$%.2f\n", res.sum)
def fromXML(node: scala.xml.Node): CCTherm =
new CCTherm {
val description = (node \ "description").text
val yearMade = (node \ "yearMade").text.toInt
val dateObtained = (node \ "dateObtained").text
val bookPrice = (node \ "bookPrice").text.toInt
val purchasePrice = (node \ "purchasePrice").text.toInt
val condition = (node \ "condition").text.toInt
}
This code searches through an input XML node, named node, to find each of the six pieces of data needed to specify a CCTherm. The data that is text is extracted with .text and left as is.
val pp = new xml.PrettyPrinter(80, 4) // 行宽 80,缩进为 4
结果是字符串
A pattern embedded in {} can use the full Scala pattern language, including binding new variables, performing type tests, and ignoring content using the _ and _* patterns. Here is a simple example:
def proc(node: scala.xml.Node): String =
node match {
case {contents} => "It's an a: "+ contents
case {contents} => "It's a b: "+ contents
case _ => "It's something else."
}
scala> proc(apple)
res16: String = It's an a: apple
scala> proc(banana)
res17: String = It's a b: banana
scala> proc(
res18: String = It's something else.
val catalog =
catalog match {
case
for (therm @
}
processing: hot dog #5
processing: Sprite Boy