Scala - 修改任意XML元素的值

时间:2017-01-22 17:50:36

标签: scala scala-xml

我想在运行时选择xml中的任意元素并更新其值。例如,给定xml,如

<root>
  <abc>123</abc>
  <def>456</def>
</root>

我想在运行时(不是硬编码)任意选择<abc><def>并更新其值。我在相关链接中发现了很多问题,但所有解决方案硬代码标签名称都在前面。

我尝试了将元素名称和新值作为参数的函数,如

object RuleFactory {

  // This function should not hard code literals "abc" or "def"
  def createRuleTransformer(name:String, value : String) : RuleTransformer = {
    new RuleTransformer(new RewriteRule {
      override def transform(n: Node): Seq[Node] = n match {
        case elem @ Elem(prefix, label, attribs, scope, _) if elem.label.equalsIgnoreCase(name) => Elem(prefix, label, attribs, scope, false, Text(value))
        case other => other
      }
    })
  }

}

object RuleFactory {
  def createRuleTransformer(name:String, value : String) : RuleTransformer = {
    new RuleTransformer(new RewriteRule {
      override def transform(n: Node): Seq[Node] = n match {
        case elem : Elem if elem.label.equalsIgnoreCase(name) => elem copy (child = Text(value) flatMap (this transform))
        case other => other
      }
    })
  }
}

但是当我执行

转换时,两者都不会打印更新的xml
val trasnformer = RuleFactory.createRuleTransformer("def", "2") // These params will be random
println(trasnformer(InputXml))

RewriteRule有可能吗?

1 个答案:

答案 0 :(得分:0)

来自https://github.com/scala/scala-xml/issues/129

由于Scala的词法范围规则,事实证明这是不幸的名称冲突。这是这个班级成员的结果:

http://www.scala-lang.org/api/current/scala-xml/scala/xml/transform/RewriteRule.html#name:String

https://github.com/scala/scala-xml/blob/4c09977/src/main/scala/scala/xml/transform/RewriteRule.scala#L23

更改变量名解决问题。这是更新的代码。

object RuleFactory {

  def createRuleTransformer(key:String, value : String) : RuleTransformer = {
    new RuleTransformer(new RewriteRule {
      override def transform(n: Node): Seq[Node] = n match {
        case elem @ Elem(prefix, label, attribs, scope, _) if elem.label.equalsIgnoreCase(key) =>
          Elem(prefix, label, attribs, scope, false, Text(value))
        case other => other
      }
    })
  }

}