Scala:如何从某个集合创建 XML 节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/215767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:18:16  来源:igfitidea点击:

Scala: how to create XML nodes from some collection

xmlscala

提问by Germán

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 nodes? I know how to use { braces } in an XML expression to put a value, but this is a collection of values. Do I need to iterate explicitly or is there something better?

如何使用该数据作为节点创建 XML 值?我知道如何在 XML 表达式中使用 {括号} 来放置一个值,但这是一个值的集合。我需要显式迭代还是有更好的方法?

val myXml = <people>{ /* what here?! */ }</people>

The resulting value should be something like:

结果值应该是这样的:

<people><person><name>joe</name><age>40</age></person>
<person><name>mary</name><age>39</age></person></people>

回答by Aaron Maenpaa

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

由于它是一种函数式编程语言 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)
    }
}

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>

回答by hishadow

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

为了完整起见,您还可以使用 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))

(fixed error noted by Woody Folsom)

(修正了伍迪福尔瑟姆指出的错误)

回答by hishadow

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

实际上,yield person.toXml() 行不适合我编译,但 yield person.toXml(不带括号)可以。原始版本抱怨“重载方法值应用”,即使我更改了“ToXml”的定义以显式返回 scala.xml.Elem