如果你有类似的话:
val myStuff = Array(Person("joe",40), Person("mary", 35))
如何使用该数据创建XML值作为节点?我知道如何在XML表达式中使用{braces}来放置值,但这是一组值。我需要明确迭代还是有更好的东西?
val myXml = <people>{ /* what here?! */ }</people>
结果值应该是:
<people><person><name>joe</name><age>40</age></person>
<person><name>mary</name><age>39</age></person></people>
答案 0 :(得分:21)
因为它是一种函数式编程语言,所以Array.map可能就是您所需要的:
class Person(name : String, age : Int){
def toXml() = <person><name>{ name }</name><age>{ age }</age></person>
}
object xml {
val people = List(
new Person("Alice", 16),
new Person("Bob", 64)
)
val data = <people>{ people.map(p => p.toXml()) }</people>
def main(args : Array[String]){
println(data)
}
}
结果:
<people><person><name>Alice</name><age>16</age></person><person><name>Bob</name><age>64</age></person></people>
格式化结果(为了更好的阅读):
<people>
<person>
<name>Alice</name>
<age>16</age>
</person>
<person>
<name>Bob</name>
<age>64</age>
</person>
</people>
答案 1 :(得分:5)
为完整起见,您还可以使用for..yield(或函数调用):
import scala.xml
case class Person(val name: String, val age: Int) {
def toXml(): xml.Elem =
<person><name>{ name }</name><age>{ age }</age></person>
}
def peopleToXml(people: List[Person]): xml.Elem = {
<people>{
for {person <- people if person.age > 39}
yield person.toXml
}</people>
}
val data = List(Person("joe",40),Person("mary", 35))
println(peopleToXml(data))
(Woody Folsom指出的固定错误)
答案 2 :(得分:0)
实际上,行产生person.toXml()不能为我编译,但是产生person.toXml(没有括号)。即使我更改了'ToXml'的def以显式返回scala.xml.Elem
,原始版本也会抱怨'重载方法值适用'