看看這對你的作品:
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))
}
}
有一對夫婦的問題。首先,爲了以您想要的方式在撥打map
時使用insertRefIntoXml
,它只需要一個參數,而不是兩個參數。爲了解決這個問題,我創建了一個局部函數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))
這使我想到第二個問題。我正在修整,以便匹配語句正確匹配。當我運行代碼時,我相信它會提供你想要的輸出。
你可以顯示之前的XML和所需的XML之後? – cmbaxter
@cmbaxter添加了一個指向我想要做的事情的前一個問題的鏈接 – bharal