1

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

我在这里做错了什么?

4

1 回答 1

1

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

于 2017-01-25T07:04:59.420 回答