How to change attribute on Scala XML Element
Posted
by Dave
on Stack Overflow
See other posts from Stack Overflow
or by Dave
Published on 2010-04-02T22:43:57Z
Indexed on
2010/04/02
22:53 UTC
Read the original article
Hit count: 351
I have an XML file that I would like to map some attributes of in with a script. For example:
<a>
<b attr1 = "100" attr2 = "50">
</a>
might have attributes scaled by a factor of two:
<a>
<b attr1 = "200" attr2 = "100">
</a>
This page has a suggestion for adding attributes but doesn't detail a way to map a current attribute with a function (this way would make that very hard): http://www.scalaclass.com/book/export/html/1
What I've come up with is to manually create the XML (non-scala) linked-list... something like:
// 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
}
Its hideous, wordy, and needlessly re-orders the attributes in the output, which is bad for my current project due to some bad client code. Is there a scala-esque way to do this?
© Stack Overflow or respective owner