ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 02.01.2026

Просмотров: 3398

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

Chapter 28

Working with XML

This chapter introduces Scala’s support for XML. After discussing semistructured data in general, it shows the essential functionality in Scala for manipulating XML: how to make nodes with XML literals, how to save and load XML to files, and how to take apart XML nodes using query methods and pattern matching. This chapter is just a brief introduction to what is possible with XML, but it shows enough to get you started.

28.1 Semi-structured data

XML is a form of semi-structured data. It is more structured than plain strings, because it organizes the contents of the data into a tree. Plain XML is less structured than the objects of a programming language, though, as it admits free-form text between tags and it lacks a type system.1

Semi-structured data is very helpful any time you need to serialize program data for saving in a file or shipping across a network. Instead of converting structured data all the way down to bytes, you convert it to and from semi-structured data. You then use pre-existing library routines to convert between semi-structured data and binary data, saving your time for more important problems.

There are many forms of semi-structured data, but XML is the most widely used on the Internet. There are XML tools on most operating systems, and most programming languages have XML libraries available. Its popularity is self-reinforcing. The more tools and libraries are developed

1There are type systems for XML, such as XML Schemas, but they are beyond the scope of this book.

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

Section 28.2

Chapter 28 · Working with XML

656

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.

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index


Section 28.3

Chapter 28 · Working with XML

657

Those are the basics. Two other things you should know are, first, there is a shorthand notation for a start tag followed immediately by its matching end tag. Simply write one tag with a slash put after the tag’s label. Such a tag comprises an empty element. Using an empty element, the previous example could just as well be written as follows:

<pod>Three <peas/> in the </pod>

Second, start tags can have attributes attached to them. An attribute is a name-value pair written with an equals sign in the middle. The attribute name itself is plain, unstructured text, and the value is surrounded by either double quotes ("") or single quotes (''). Attributes look like this:

<pod peas="3" strings="true"/>

28.3 XML literals

Scala lets you type in XML as a literal anywhere that an expression is valid. Simply type a start tag and then continue writing XML content. The compiler will go into an XML-input mode and will read content as XML until it sees the end tag matching the start tag you began with:

scala> <a>

This is some XML.

Here is a tag: <atag/> </a>

res0: scala.xml.Elem = <a>

This is some XML.

Here is a tag: <atag></atag> </a>

The result of this expression is of type Elem, meaning it is an XML element with a label (“a”) and children (“This is some XML. . . ,” etc.). Some other important XML classes are:

Class Node is the abstract superclass of all XML node classes.

Class Text is a node holding just text. For example, the “stuff” part of

<a>stuff</a> is of class Text.

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

Section 28.3

Chapter 28 · Working with XML

658

Class NodeSeq holds a sequence of nodes. Many methods in the XML library process NodeSeqs in places you might expect them to process individual Nodes. You can still use such methods with individual nodes, however, since Node extends from NodeSeq. This may sound weird, but it works out well for XML. You can think of an individual Node as a one-element NodeSeq.

You are not restricted to writing out the exact XML you want, character for character. You can evaluate Scala code in the middle of an XML literal by using curly braces ({}) as an escape. Here is a simple example:

scala> <a> {"hello"+", world"} </a>

res1: scala.xml.Elem = <a> hello, world </a>

A braces escape can include arbitrary Scala content, including further XML literals. Thus, as the nesting level increases, your code can switch back and forth between XML and ordinary Scala code. Here’s an example:

scala> val yearMade = 1955 yearMade: Int = 1955

scala> <a> { if (yearMade < 2000) <old>{yearMade}</old> else xml.NodeSeq.Empty }

</a>

res2: scala.xml.Elem = <a> <old>1955</old>

</a>

If the code inside the curly braces evaluates to either an XML node or a sequence of XML nodes, those nodes are inserted directly as is. In the above example, if yearMade is less than 2000, it is wrapped in <old> tags and added to the <a> element. Otherwise, nothing is added. Note in the above example that “nothing” as an XML node is denoted with xml.NodeSeq.Empty.

An expression inside a brace escape does not have to evaluate to an XML node. It can evaluate to any Scala value. In such a case, the result is converted to a string and inserted as a text node:

scala> <a> {3 + 4} </a>

res3: scala.xml.Elem = <a> 7 </a>

Any <, >, and & characters in the text will be escaped if you print the node back out:

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index



Section 28.4

Chapter 28 · Working with XML

659

scala> <a> {"</a>potential security hole<a>"} </a> res4: scala.xml.Elem = <a> </a>potential security hole<a> </a>

To contrast, if you create XML with low-level string operations, you will run into traps such as the following:

scala> "<a>" + "</a>potential security hole<a>" + "</a>" res5: java.lang.String = <a></a>potential security hole<a></a>

What happens here is that a user-supplied string has included XML tags of its own, in this case </a> and <a>. This behavior can allow some nasty surprises for the original programmer, because it allows the user to affect the resulting XML tree outside of the space provided for the user inside the <a> element. You can prevent this entire class of problems by always constructing XML using XML literals, not string appends.

28.4 Serialization

You have now seen enough of Scala’s XML support to write the first part of a serializer: conversion from internal data structures to XML. All you need for this are XML literals and their brace escapes.

As an example, suppose you are implementing a database to keep track of your extensive collection of vintage Coca-Cola thermometers. You might make the following internal class to hold entries in the catalog:

abstract class CCTherm {

 

val description: String

 

val yearMade: Int

 

val dateObtained: String

 

val bookPrice: Int

// in US cents

val purchasePrice: Int

// in US cents

val condition: Int

// 1 to 10

override def toString = description

}

This is a straightforward, data-heavy class that holds various pieces of information such as when the thermometer was made, when you got it, and how much you paid for it.

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index


Section 28.4

Chapter 28 · Working with XML

660

To convert instances of this class to XML, simply add a toXML method that uses XML literals and brace escapes, like this:

abstract class CCTherm {

...

def toXML = <cctherm>

<description>{description}</description>

<yearMade>{yearMade}</yearMade>

<dateObtained>{dateObtained}</dateObtained>

<bookPrice>{bookPrice}</bookPrice>

<purchasePrice>{purchasePrice}</purchasePrice>

<condition>{condition}</condition>

</cctherm>

}

Here is the method in action:

scala> val therm = new CCTherm {

val description = "hot dog #5" val yearMade = 1952

val dateObtained = "March 14, 2006" val bookPrice = 2199

val purchasePrice = 500 val condition = 9

}

therm: CCTherm = hot dog #5

scala> therm.toXML res6: scala.xml.Elem = <cctherm>

<description>hot dog #5</description> <yearMade>1952</yearMade> <dateObtained>March 14, 2006</dateObtained> <bookPrice>2199</bookPrice> <purchasePrice>500</purchasePrice> <condition>9</condition>

</cctherm>

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

Section 28.5

Chapter 28 · Working with XML

661

Note

The “new CCTherm” expression in the previous example works even though CCTherm is an abstract class, because this syntax actually instantiates an anonymous subclass of CCTherm. Anonymous classes were described in Section 20.5.

By the way, if you want to include a curly brace (‘{’ or ‘}’) as XML text, as opposed to using them to escape to Scala code, simply write two curly braces in a row:

scala> <a> {{{{brace yourself!}}}} </a>

res7: scala.xml.Elem = <a> {{brace yourself!}} </a>

28.5 Taking XML apart

Among the many methods available for the XML classes, there are three in particular that you should be aware of. They allow you to take apart XML without thinking too much about the precise way XML is represented in Scala. These methods are based on the XPath language for processing XML. As is common in Scala, you can write them directly in Scala code instead of needing to invoke an external tool.

Extracting text. By calling the text method on any XML node you retrieve all of the text within that node, minus any element tags:

scala> <a>Sounds <tag/> good</a>.text res8: String = Sounds good

Any encoded characters are decoded automatically:

scala> <a> input ---> output </a>.text res9: String = input ---> output

Extracting sub-elements. If you want to find a sub-element by tag name, simply call \ with the name of the tag:

scala> <a><b><c>hello</c></b></a> \ "b"

res10: scala.xml.NodeSeq = <b><c>hello</c></b>

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index