scala - xml 使用变量和 RewriteRule 的转换

scala - xml transformation using variable and RewriteRule

我正在玩 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>

我做错了什么?

问题是匹配是在 RewriteRule 中定义的,恰好有一个 name 字段(在我的测试中它的值为 "<function1>")。该字段在外部范围内隐藏您的 name 变量。重命名您的变量可以解决问题。