无法使用参数创建xml

时间:2013-12-26 10:44:43

标签: xml scala

我有一个方法:

def method1(elemName: String, body: Elem) = 
  <someXml>
    <{elemName}>
      body
    </{elemName}>
  </someXml>

由于<{elemName}>body而抱怨,其中body是xml,elemName是字符串。它是否为一个字符串,以避免重复传递xml中的2(打开和关闭)参数。

为什么,我该如何解决?

1 个答案:

答案 0 :(得分:3)

您必须使用方法Elem手动创建名为elemName的{​​{1}}:

Elem.apply

使用属性:

import xml._

val body = <body />
val elemName = "elemName"

val elem =
  Elem(prefix = null,
       label = elemName,
       attributes = Null,
       scope = TopScope,
       minimizeEmpty = true,
       body)
<someXml>{elem}</someXml>
// <someXml>{elem}</someXml>

使用val attrs = List("k1" -> "v1", "k2" -> "v2").reverse. foldLeft(Null: MetaData){ case (as, (k, v)) => new UnprefixedAttribute(k, v, as) } val elem = Elem(prefix = null, label = elemName, attributes = attrs, scope = TopScope, minimizeEmpty = true, body) <someXml>{elem}</someXml> // <someXml><elemName k1="v1" k2="v2"><body/></elemName></someXml>

xmlns