scala - 使用变量和RewriteRule进行xml转换

时间:2017-01-24 23:37:49

标签: scala scala-xml

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

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

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