I have a list of strings and I need to join them together with <br/> tags in between. So starting from:
val list = List("line1", "line2", "line3")
I need to end up with a NodeSeq of:
It's possible the list contains only one element, in which case I should end up with a NodeSeq just of Text("line1").
Is there a one-liner to do this, using one of the higher order functions on list? I've tried to play around with foldLeft but can't seem to get it to do what I want.
list.map(scala.xml.Text(_):scala.xml.NodeSeq).reduce(_ ++ <br /> ++ _)
Note that we have to widen the type to
scala.xml.NodeSeq manually as
Text is too restrictive for the
reduce method. The more concise
list.map(scala.xml.Text).reduce(_ ++ <br /> ++ _)
If you don't mind using Scalaz, there's
list.map(xml.Text(_): xml.Node).intersperse(<br/>): xml.NodeSeq
Agree with what Debilski has answered. Just another way of achieving the same is,
XML.loadString("<root>" + list.mkString("<br/>") + "</root>").child:NodeSeq
But using map/reduce is a much cleaner approach.