【发布时间】:2015-07-31 19:01:06
【问题描述】:
我的 scala 代码目前最终用我添加的新标签替换了我的 xml 文件的整个部分。我希望它只将标签添加一次作为 ClientConfig 的子标签,但它会用它自己替换本节中存在的所有标签。
val data = XML.load(file)
val p = new XMLPrettyPrinter(2)
val tryingtoAdd = addNewEntry(data,host,env)
p.write(tryingtoAdd)(System.out)
其中 host=bob 和 env=flat 是之前定义的,addNewEntry 定义如下
private def isCorrectLocation(parent: Elem, node: Elem, host: String): Boolean = {
parent.label == "ClientConfig" && node.label == "host"
}
def addNewEntry(elem:Elem, host: String, env: String): Elem ={
val toAdd = <host name={host} env={env} />
def addNew(current: Elem): Elem = current.copy(
child = current.child.map {
case e: Elem if isCorrectLocation(current, e, host) ⇒ toAdd
case e: Elem ⇒ addNew(e)
case other ⇒ other
}
)
addNew(elem)
}
它产生的xml是
<ClientConfig>
<host name="bob" env="flat"/>
<host name="bob" env="flat"/>
<host name="bob" env="flat"/>
<host name="bob" env="flat"/>
</ClientConfig>
我希望它只是将它附加为 ClientConfig 的单个子项,例如文件中已经存在最后三个子项的地方
<ClientConfig>
<host name="bob" env="flat"/>
<host name="george" env="flat"/>
<host name="alice" env="flat"/>
<host name="bernice" env="flat"/>
</ClientConfig>
我该怎么办?例如python有一个简单的插入方法
【问题讨论】:
标签: xml scala scala-2.10 scala-xml