Scala: how to create XML nodes from some collection

前端 未结 3 931
执念已碎
执念已碎 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: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 =
        <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))
    

    (fixed error noted by Woody Folsom)

    0 讨论(0)
  • 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() = <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)
        }
    }
    

    Results in:

    <people><person><name>Alice</name><age>16</age></person><person><name>Bob</name><age>64</age></person></people>
    

    A formatted result (for a better read):

    <people>
       <person>
          <name>Alice</name>
          <age>16</age>
       </person>
       <person>
          <name>Bob</name>
          <age>64</age>
       </person>
    </people>
    
    0 讨论(0)
  • 2020-12-16 00:27

    Actually, the line yield person.toXml() does not compile for me, but yield person.toXml (without the parentheses) does. The original version complains of 'overloaded method value apply' even if I change the def of 'ToXml' to explicitly return a scala.xml.Elem

    0 讨论(0)
提交回复
热议问题