看看这是否适合你:
object TestXml {
  def main(args: Array[String]) {
    val xml = 
      <root>        
    <here>
      <dealID>foo</dealID>
    </here>        
  </root>
    println(insertRefIntoXml(2, xml))
  }
  def insertRefIntoXml(ref: Int, entry: Node): Node = {    
    def doInsertRef(n:Node):Node = {    
      n match {
        case <root>{ mainRoot @ _* }</root> => <root>{ mainRoot.map(doInsertRef)}</root>
        case <here><dealID>{ contents }</dealID></here> => <here><dealID>{ ref }</dealID></here>
        case other @ _ => other
      }       
    }
    doInsertRef(scala.xml.Utility.trim(entry))
  }
}
有几个问题。首先,为了以您想要的方式insertRefIntoXml在调用中使用map,它只需要一个 arg 而不是两个。为了解决这个问题,我创建了一个本地函数 def,然后ref通过闭包从那里获取值。你也可以像这样解决这个问题:
  def insertRefIntoXml(ref: Int, entry: Node): Node = {       
    entry match {
      case <root>{ mainRoot @ _* }</root> => <root>{ mainRoot.map(insertRefIntoXml(ref, _))}</root>
      case <here><dealID>{ contents }</dealID></here> => <here><dealID>{ ref }</dealID></here>
      case other @ _ => other
    }       
  }
然后这样称呼它:
insertRefIntoXml(2, scala.xml.Utility.trim(xml))
这让我想到了第二个问题。我正在修剪以便匹配语句正确匹配。当我运行代码时,我相信它会给出你想要的输出。