我正在玩scala xml转换,而我的下面的程序并没有给我预期的输出。
import scala.xml.{Elem, Node, Text}
import scala.xml.transform.{RewriteRule, RuleTransformer}
object XmlTransform extends App {
val name = "contents"
val value = "2"
val InputXml : Node =
<root>
<subnode>1</subnode>
<contents>1</contents>
</root>
val transformer = new RuleTransformer(new RewriteRule {
override def transform(n: Node): Seq[Node] = n match {
case elem @ Elem(prefix, label, attribs, scope, _) if elem.label == name =>
Elem(prefix, label, attribs, scope, false, Text(value))
case other => other
}
})
println(transformer(InputXml))
}
它打印xml而不进行任何转换。
<root>
<subnode>1</subnode>
<contents>1</contents>
</root>
如果我替换(虽然我不想要那个)名称变量在&#34; case if&#34;声明如
case elem @ Elem(prefix, label, attribs, scope, _) if elem.label == "contents" =>
Elem(prefix, label, attribs, scope, false, Text(value))
打印出预期转换的xml
<root>
<subnode>1</subnode>
<contents>2</contents>
</root>
我在这里做错了什么?
答案 0 :(得分:1)
问题是匹配是在恰好有name
字段的RewriteRule
内定义的(在我的测试中它的值为"<function1>"
)。此字段将隐藏外部范围中的name
变量。重命名变量可以解决问题。