如果你有类似的东西:
val myStuff = Array(Person("joe",40), Person("mary", 35))
如何使用该数据创建XML值作为节点?我知道如何在XML表达式中使用{braces}来放置值,但这是一组值.我需要明确迭代还是有更好的东西?
val myXml ={ /* what here?! */ }
结果值应该是这样的:
joe 40 mary 39
Aaron Maenpa.. 21
由于它是一种函数式编程语言,Array.map可能正是您所寻找的:
class Person(name : String, age : Int){ def toXml() =} object xml { val people = List( new Person("Alice", 16), new Person("Bob", 64) ) val data = { name } { age } { people.map(p => p.toXml()) } def main(args : Array[String]){ println(data) } }
结果是:
Alice 16 Bob 64
格式化结果(为了更好的阅读):
Alice 16 Bob 64
hishadow.. 5
为完整起见,您还可以使用for..yield(或函数调用):
import scala.xml case class Person(val name: String, val age: Int) { def toXml(): xml.Elem =} def peopleToXml(people: List[Person]): xml.Elem = { { name } { age } { for {person <- people if person.age > 39} yield person.toXml } } val data = List(Person("joe",40),Person("mary", 35)) println(peopleToXml(data))
(Woody Folsom指出的固定误差)
由于它是一种函数式编程语言,Array.map可能正是您所寻找的:
class Person(name : String, age : Int){ def toXml() =} object xml { val people = List( new Person("Alice", 16), new Person("Bob", 64) ) val data = { name } { age } { people.map(p => p.toXml()) } def main(args : Array[String]){ println(data) } }
结果是:
Alice 16 Bob 64
格式化结果(为了更好的阅读):
Alice 16 Bob 64
为完整起见,您还可以使用for..yield(或函数调用):
import scala.xml case class Person(val name: String, val age: Int) { def toXml(): xml.Elem =} def peopleToXml(people: List[Person]): xml.Elem = { { name } { age } { for {person <- people if person.age > 39} yield person.toXml } } val data = List(Person("joe",40),Person("mary", 35)) println(peopleToXml(data))
(Woody Folsom指出的固定误差)