Scala: how to create XML nodes from some collection

前端 未结 3 934
执念已碎
执念已碎 2020-12-15 23:20

If you have something like:

val myStuff = Array(Person(\"joe\",40), Person(\"mary\", 35))

How do you create an XML value with that data as

3条回答
  •  Happy的楠姐
    2020-12-16 00:00

    For completeness, you can also use for..yield (or function calls):

    import scala.xml
    
    case class Person(val name: String, val age: Int) {
      def toXml(): xml.Elem =
        { name }{ age }
    }
    
    def peopleToXml(people: List[Person]): xml.Elem = {
      {
        for {person <- people if person.age > 39}
          yield person.toXml
      }
    }
    
    val data = List(Person("joe",40),Person("mary", 35))
    println(peopleToXml(data))
    

    (fixed error noted by Woody Folsom)

提交回复
热议问题