I'm playing with scala xml transformation and my below program doesn't give me expected output.
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))
}
It prints xml without any transformation.
<root>
<subnode>1</subnode>
<contents>1</contents>
</root>
If I replace(though I didn't want that) name variable in "case if" statement like
case elem @ Elem(prefix, label, attribs, scope, _) if elem.label == "contents" =>
Elem(prefix, label, attribs, scope, false, Text(value))
it prints out expected transformed xml
<root>
<subnode>1</subnode>
<contents>2</contents>
</root>
What am I doing wrong here?
The problem is that the match is defined inside the RewriteRule
that happens to have a name
field (in my test it had the value "<function1>"
). This field shadows your name
variable in the outer scope. Renaming your variable solves the problem.