Scala - 用特定文本替换 xml 元素 [英] Scala - replace xml element with specific text
本文介绍了Scala - 用特定文本替换 xml 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有这个 XML
<a>blah</a>
我想把它改成
<a>someValueIDoNotKnowAtCompileTime</a>
目前,我正在查看这个问题.但是,这只是将值更改为2"
Currently, I am looking at this SO question . However, this just changes the value to "2"
我想要的是完全一样的东西,但能够定义值(以便它可以在运行时更改 - 我正在从文件中读取值!)
What i want is exactly the same thing, but to be able to define the value (so that it can change at runtime - i am reading the values from a file!)
我尝试将值传递给重写的方法,但这不起作用 - 编译错误无处不在(显然)
I tried passing the value into the overridden methods, but that didn't work - compile errors everywhere (obviously)
如何使用动态值更改静态 xml?
How can i change static xml with dynamic values?
添加代码
var splitString = someString.split("/t") //where someString is a line from a file
val action = splitString(0)
val ref = splitString(1)
xmlMap.get(action) match { //maps the "action" string to some XML
case Some(entry) => {
val xmlToSend = insertRefIntoXml(ref,entry)
//for the different XML, i want to put the string "ref" in an appropriate place
}
...
推荐答案
例如:
scala> val x = <foo>Hi</foo>
x: scala.xml.Elem = <foo>Hi</foo>
scala> x match { case <foo>{what}</foo> => <foo>{System.nanoTime}</foo> }
res1: scala.xml.Elem = <foo>213370280150006</foo>
更新链接示例:
import scala.xml._
import System.{ nanoTime => now }
object Test extends App {
val InputXml : Node =
<root>
<subnode> <version>1</version> </subnode>
<contents> <version>1</version> </contents>
</root>
def substitution = now // whatever you like
def updateVersion(node: Node): Node = node match {
case <root>{ ch @ _* }</root> => <root>{ ch.map(updateVersion )}</root>
case <subnode>{ ch @ _* }</subnode> => <subnode>{ ch.map(updateVersion ) }</subnode>
case <version>{ contents }</version> => <version>{ substitution }</version>
case other @ _ => other
}
val res = updateVersion(InputXml)
val pp = new PrettyPrinter(width = 2, step = 1)
Console println (pp format res)
}
这篇关于Scala - 用特定文本替换 xml 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文