我正在玩 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>
如果我在“case if”语句中替换(虽然我不想要那个)名称变量,例如
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>
我在这里做错了什么?