假设我将您的示例 xml 代码放在 Country.xml 中。
<Countries>
<Country>
<Name>Italy</Name>
<Continent>Europe</Continent>
</Country>
<Country>
<Name>Japan</Name>
<Continent>Asia</Continent>
</Country>
</Countries>
以下是我尝试完成的方法
object XMLLoader extends App {
def toBeAddedEntry(name: String, continent: String) =
<Country>
<Name>{ name }</Name>
<Continent>{ continent }</Continent>
</Country>
// For problem 1 How to add a new Node
def addNewEntry(originalXML: Elem, name: String, continent: String) = {
originalXML match {
case <Countries>{ innerProps @ _* }</Countries> => {
<Countries> {
innerProps ++ toBeAddedEntry(name, continent)
}</Countries>
}
case other => other
}
}
// For problem 2 How to delete node with element Name with certain value
def deleteEntry(originalXML: Elem, nameValue: String) = {
originalXML match {
/*
Considering you just start coding in Scala, the following explanation may help:
Here Elem is used as Extractor, actually the unapplySeq in Elem object is invoked
def unapplySeq(n: Node) = n match {
case _: SpecialNode | _: Group => None
case _ => Some((n.prefix, n.label, n.attributes, n.scope, n.child))
}
Then we use sequence pattern(match against a sequence without specifying how long it can be) to
extract child of originalXML and do the filtering job
*/
case e @ Elem(_, _, _, _, countries @ _*) => {
/*
original is kind of like
<Country>
<Name>Japan</Name>
<Continent>Asia</Continent>
</Country>
*/
val changedNodes = countries filter { country =>
(original \ "Name").exists(elem => elem.text != nameValue)
}
e.copy(child = changedNodes)
}
case _ => originalXML
}
}
// define your own way to load Country.xml
val originalXML = XML.load(getClass.getClassLoader.getResourceAsStream("Country.xml"))
val printer = new scala.xml.PrettyPrinter(80,5)
println(printer.format(addNewEntry(originalXML, "China", "Asia")))
println(printer.format(deleteEntry(originalXML, "Japan")))
}
结果如下:
<Countries>
<Country>
<Name>Italy</Name>
<Continent>Europe</Continent>
</Country>
<Country>
<Name>Japan</Name>
<Continent>Asia</Continent>
</Country>
<Country>
<Name>China</Name>
<Continent>Asia</Continent>
</Country>
</Countries>
<Countries>
<Country>
<Name>Italy</Name>
<Continent>Europe</Continent>
</Country>
</Countries>
剩下的部分是关于将 Node 写回 Country.xml。无论如何,希望它有所帮助。