我有一个类似于 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>
确实不起作用的。
有什么建议么 ?