如何将scala Xml元素列表转换为单个scala元素?

时间:2012-03-15 00:16:59

标签: xml scala scala-xml

所以我有

val list:List[Any];
def toElement(a:Any):scala.xml.Elem;

我想写点像

val result = <span> {list.map(toElement).toElem} <span>

2 个答案:

答案 0 :(得分:1)

如果我理解正确的话,我认为你所追求的可能是这样的:

// List of different types
val list: List[Any] = List("one", 2, "three", 4:Long)

// Conversion function for type 'Any' - (note .toElem or .toXml isn't a
// member of 'Any' - so that's why we need to create this)
def toElement(a: Any): scala.xml.Elem = <hello>{ a.toString }</hello>

// Usage example
val result = <span>{ list.map( toElement(_) ) }</span>    

但我想这实际上取决于你在列表中期望的对象类型,以及你希望它们最终看起来像什么类型的XML元素。

答案 1 :(得分:0)

只是一个想法......

val list:List[Any] = List(1, 2, "test", 3.5)

def toElement(a:Any):scala.xml.Elem = {
  scala.xml.Elem(null, a.toString, scala.xml.Null, scala.xml.TopScope)
}

val result = <span> { list map toElement } </span>

结果

<span> <1></1><2></2><test></test><3.5></3.5> </span>