我有一个XML文件,我想用脚本映射其中的一些属性。例如:
<a>
<b attr1 = "100" attr2 = "50"/>
</a>
可能会有属性按两倍比例缩放:
<a>
<b attr1 = "200" attr2 = "100"/>
</a>
这个页面提供了一些建议来添加属性,但没有详细介绍如何将当前的属性映射到一个函数(这将使这个过程非常困难):http://www.scalaclass.com/book/export/html/1
我想到的方法是手动创建XML(非Scala)链表......类似于:
// a typical match case for running thru XML elements:
case Elem(prefix, e, attributes, scope, children @ _*) => {
var newAttribs = attributes
for(attr <- newAttribs) attr.key match {
case "attr1" => newAttribs = attribs.append(new UnprefixedAttribute("attr1", (attr.value.head.text.toFloat * 2.0f).toString, attr.next))
case "attr2" => newAttribs = attribs.append(new UnprefixedAttribute("attr2", (attr.value.head.text.toFloat * 2.0f).toString, attr.next))
case _ =>
}
Elem(prefix, e, newAttribs, scope, updateSubNode(children) : _*) // set new attribs and process the child elements
}
它太丑陋,过于冗长,而且在输出中不必要地重新排列属性,这对我的当前项目很糟糕,因为有一些糟糕的客户端代码。是否有类似Scala的方法可以解决这个问题?