in response to XML’s popularity, the more likely software engineers are to choose XML as part of their formats. If you write software that communicates over the Internet, then sooner or later you will need to interact with some service that speaks XML.
For all of these reasons, Scala includes special support for processing XML. This chapter shows you Scala’s support for constructing XML, processing it with regular methods, and processing it with Scala’s pattern matching. In addition to these nuts and bolts, the chapter shows along the way several common idioms for using XML in Scala.
28.2 XML overview
XML is built out of two basic elements, text and tags.2 Text is, as usual, any sequence of characters. Tags, written like <pod>, consist of a less-than sign, an alphanumeric label, and a greater than sign. Tags can be start or end tags. An end tag looks just like a start tag except that it has a slash just before the tag’s label, like this: </pod>.
Start and end tags must match each other, just like parentheses. Any start tag must eventually be followed by an end tag with the same label. Thus the following is illegal:
// Illegal XML
One <pod>, two <pod>, three <pod> zoo
Further, the contents of any two matching tags must itself be valid XML. You cannot have two pairs of matching tags overlap each other:
// Also illegal
<pod>Three <peas> in the </pod></peas>
You could, however, write it like this:
<pod>Three <peas></peas> in the </pod>
Since tags are required to match in this way, XML is structured as nested elements. Each pair of matching start and end tags forms an element, and elements may be nested within each other. In the above example, the entirety of <pod>Three <peas></peas> in the </pod> is an element, and
<peas></peas> is an element nested within it.
2The full story is more complicated, but this is enough to be effective with XML.