See if this works for you:
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))
}
}
There were a couple of issues. First, in order to use insertRefIntoXml
in a call to map
in the way that you wanted to, it need to only have one arg and not two. To fix that, I created a local function def and then get the value from ref
in there via closure. You could also solve this problem like this instead:
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
}
}
And then call it like this:
insertRefIntoXml(2, scala.xml.Utility.trim(xml))
Which brings me to the second issue. I'm trimming so that the match statements match up correctly. When I run the code, I believe it gives the output you desire.