0

我有一个类似于 Scala 的问题——修改 xml 中的嵌套元素 我在这篇文章中复制了相同的代码。我正在尝试修改元素中的内容,我必须调用一个函数来获取内容。例如。

object test extends App {
  val InputXml: Node =
    <root>
      <contents>
        <version>1</version>
      </contents>
    </root>

  object t1 extends RewriteRule {
    override def transform(n: Node): Seq[Node] = {
      println("transforming '" + n + "'")
      n match {
        case Elem(prefix, "version", attribs, scope, _*) =>
          Elem(prefix, "version", attribs, scope, true, Text(computeVersion()))

        case other => other
      }
    }

    def computeVersion() = {
      println("computeVersion called")
      "3.0"
    }
  }

  object rt1 extends RuleTransformer(t1)
  val res = rt1(InputXml)
  val pp = new PrettyPrinter(width = 2, step = 1)
  Console println (pp format res)
}

输出是:

transforming ' '
transforming '1'
transforming '<version>1</version>'
computeVersion called
transforming '<version>1</version>'
computeVersion called
transforming '1'
transforming '<version>1</version>'
computeVersion called
transforming '<version>1</version>'
computeVersion called
transforming '<contents> <version>3.0</version></contents>'
transforming ' '
transforming '1'
transforming '<version>1</version>'
computeVersion called
transforming '<version>1</version>'
computeVersion called
transforming '1'
transforming '<version>1</version>'
computeVersion called
transforming '<version>1</version>'
computeVersion called
transforming '<contents> <version>3.0</version></contents>'
transforming '<root><contents> <version>3.0</version></contents></root>'
<root><contents> <version>3.0</version></contents></root>

由于复杂性,computeVersion() 几乎每次都会被调用。我只想在处理实际标签时调用它。我试图用模式匹配来包围它,比如搜索<version>确实不起作用的。
有什么建议么 ?

4

1 回答 1

0

我解决了这个问题。这个问题在https://github.com/scala/scala-xml/issues/58中得到解决

虽然修复在 2.12-M3(截至今天)版本的 scala 中可用,但像我这样使用 2.11 版本的 scala 的人可以覆盖类中的 transform 方法并粘贴代码

 def transform(ns: Seq[Node]): Seq[Node] = {
    val changed = ns flatMap transform
    if (changed.length != ns.length || (changed, ns).zipped.exists(_ != _)) changed
else ns
}
于 2016-02-01T23:23:01.750 回答