Scala - 用特定文本替换xml元素

时间:2013-07-17 16:49:08

标签: xml scala

所以我有这个XMl

<a>blah</a>

我想将其改为

<a>someValueIDoNotKnowAtCompileTime</a>

目前,我正在关注this SO question。但是,这只会将值更改为“2”

我想要的是完全相同的东西,但是能够定义值(以便它可以在运行时更改 - 我正在从文件中读取值!)

我尝试将值传递给重写的方法,但这不起作用 - 在任何地方编译错误(显然)

如何使用动态值更改静态xml?

添加代码

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
    }
    ...

1 个答案:

答案 0 :(得分:3)

例如:

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)
}