tags between them. So, starti...">

Attach strings with XML node between scala

I have a list of strings and I need to combine them together with <br / "> tags between them. So, starting with:

val list = List("line1", "line2", "line3") 

I need to finish using NodeSeq:

 line1<br/>line2<br/>line3 

Perhaps the list contains only one element, in which case I should end with NodeSeq only the text ("line1").

Is there one liner for this, using one of the higher order functions in the list? I tried to play with foldLeft but can't get it to do what I want.

+8
xml scala
source share
3 answers
 list.map(scala.xml.Text(_):scala.xml.NodeSeq).reduce(_ ++ <br /> ++ _) 

Note that we need to increase the type to scala.xml.NodeSeq manually, because Text is too strict for the reduce method. More concise

 list.map(scala.xml.Text).reduce(_ ++ <br /> ++ _) 

not compiled.

+12
source share

If you do not mind using Scalaz , there intersperse :

 import scalaz._ import Scalaz._ list.map(xml.Text(_): xml.Node).intersperse(<br/>): xml.NodeSeq 
+3
source share

Agree to what Debilsky answered. Another way to achieve the same is

import scala.xml._

XML.loadString("<root>" + list.mkString("<br/>") + "</root>").child:NodeSeq

But using map / reduce is a much cleaner approach.

0
source share

All Articles