Scala: how to create XML nodes from some collection

前端 未结 3 932
执念已碎
执念已碎 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条回答
  •  既然无缘
    2020-12-16 00:26

    As it's a functional programming language Array.map is probably what you're looking for:

    class Person(name : String, age : Int){
        def toXml() = { name }{ age }
    }
    
    object xml {
        val people = List(
            new Person("Alice", 16),
            new Person("Bob", 64)
        )
    
        val data = { people.map(p => p.toXml()) }
    
        def main(args : Array[String]){
            println(data)
        }
    }
    

    Results in:

    Alice16Bob64
    

    A formatted result (for a better read):

    
       
          Alice
          16
       
       
          Bob
          64
       
    
    

提交回复
热议问题