ferdi
ferdi

Reputation: 3

Writing a list of xml nodes recursively in scala

I'm learning scala and have problem with writing an xml file.

Suppose I have a

case class Coordinate(x: Int, y: Int)

and

val l = List(Coordinate(1,3), Coordinate(2,4), Coordinate(3,5))

I need to print an xml file with the format:

<root>
  <object>
    <coord x="1" y="3"/>
    <coord x="2" y="4"/>
    <coord x="3" y="5"/>
  </object>
</root>`

I'm trying to implement it recursively so it will work on large amount of Coordinates data and multiple

<object>.

I have tried to print the output first to check the result with this:

def convertToXML(l: List[Coordinate]): Unit = {
  def eachCoordToXML(coord: Coordinate): scala.xml.Node = {
    <coord x={ coord.x.toString }  y={ coord.y.toString } />
  }

  val newObject =
    <object>
      { l.foreach(eachCoordToXML(_)) }
    </object>

  println(newObject.mkString)
}

and the result showed up something like this

<object>

</object>

Can anyone guide me here, what did I go wrong? or is there any better/more efficient way to write xml node recursively?

Upvotes: 0

Views: 297

Answers (1)

vitalii
vitalii

Reputation: 3365

You are doing everything right! You just need to use map instead of foreach!

foreach in scala returns Unit.

Upvotes: 3

Related Questions