
86
CHAPTER 3
■ COLLECTIONS AND THE JOY OF IMMUTABILITY
This RewriteRule matches nodes with the add instruction attribute. The method creates
a new element with the same attributes, but removes the
instruction attribute. It also
transforms the child nodes and appends a child node.
Let’s run this transformation:
scala> new RuleTransformer(addIt).transform(xmlBooks)
res2: Seq[scala.xml.Node] =
<books instruction="update">
<book instruction="remove" status="" name="book1"></book>
<book status="" name="book2"><added>I added this</added></book>
</books>
Note that the book2 book has child nodes. We can run the transformation with both of
the
RewriteRules:
scala> new RuleTransformer(addIt, removeIt).transform(xmlBooks)
res3: Seq[scala.xml.Node] =
<books instruction="update">
<book status="" name="book2"><added>I added this</added></book>
</books>
In this section, we’ve explored creating, parsing, and rewriting XML. Scala’s awesome
XML support makes it super-simple to write complex web-based applications. You can
create Atom or RSS feeds in just a few lines that transform database records into the
appropriate XML. You can parse incoming XML using the same constructs you use for
other data sequences, which makes transformation from XML into data structures and
objects easy and fast. Finally, Scala provides simple ways to transform XML.
In this chapter, we’ve explored Scala’s immutable data types and the power and simplicity
that they afford you. Next, let’s see how we can use the immutable data structures in a
highly concurrent situation. We’re going to do concurrency without synchronization and
see how immutability helps us out, big time.
19897ch03.fm Page 86 Thursday, April 16, 2009 4:54 PM