我正在尝试编写一个 XML 解析实用程序,该实用程序允许用户通过提供属性名称、当前属性值和他们希望属性具有的新值来修改 XML 属性。这是我的代码:
def main (args: Array[String]) {
val xml= <Rule debug="true" expression="testing"/>
val printable= replaceXMLEntryAttribute(xml, "debug", "true", "false")
println(printable)
}
/**
* This method is used to iterate over the entirety of the xml presented and modify the XML attribute desired
*/
def replaceXMLEntryAttribute(elem: Elem, attrName: String, curVal: String, desiredVal: String): Elem = {
def replace(current: Elem): Elem = current.copy(
child = current.map {
case e: Elem if isReplacementEntry(current, attrName, curVal) ⇒ generateReplacementXMLAttribute(current)
case e: Elem ⇒ replace(e)
case other⇒ other
}
)
def generateReplacementXMLAttribute(node: Elem): Elem = {
val currentXML= node.toString()
val newAttr= currentXML.replace(curVal, desiredVal)
return XML.loadString(newAttr)
}
replace(elem)
}
private def isReplacementEntry(node: Elem, attributeName: String, currentAttrValue: String): Boolean = {
val attr = "@" + attributeName
val exists = node \\ attr find { _.text == currentAttrValue }
exists match{
case None => false
case _ => true
}
所需的输出是<Rule debug="false" expression="testing"/>
程序的结果是<Rule debug="true" expression="testing"><Rule expression="testing" debug="false"/></Rule>
我只能猜测并说替换方法在这里搞砸了。