修改xml内容scala

时间:2016-01-28 06:17:24

标签: xml scala scala-xml

我有类似的问题 Scala - modifying nested elements in 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>,这实际上是无法解决的 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

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

中解决

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

 def transform(ns: Seq[Node]): Seq[Node] = {
    val changed = ns flatMap transform
    if (changed.length != ns.length || (changed, ns).zipped.exists(_ != _)) changed
else ns
}