2

所以我有这个 XML

<a>blah</a>

我想把它改成

<a>someValueIDoNotKnowAtCompileTime</a>

目前,我正在查看这个 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
    }
    ...
4

1 回答 1

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)
}
于 2013-07-17T22:15:25.013 回答