elem

Scala: Extracting data from an array of XML elements

Problem: Your XML data has an array of elements, and you need to extract the first element, second element, or more generally, the Nth element, using Scala.

Solution

The following simplified version of the XML from the Yahoo Weather API has three <forecast> elements:

Scala: Deeper XML parsing, and extracting XML tag attributes

Problem: You need to perform deep XML searches, combining the \ and \\ methods, and possibly searching directly for tag attributes.

Solution

Combine the \\ and \ methods as needed to search the XML. When you need to extract tag attributes, place an @ character before the attribute name.

Given this simplified version of the Yahoo Weather RSS Feed:

Basic Scala XPath searching with \ and \\

Problem: When writing a Scala application, you want to search an XML tree for the data you need using XPath expressions.

Solution

Use the \ and \\ methods, which are analogous to the XPath / and // expressions. The \ method returns all matching elements directly under the current node, and \\ returns all matching elements from all nodes under the current node (all descendant nodes).

To demonstrate this difference, create this XML literal:

How to extract data from XML nodes in Scala

Problem: In a Scala application, you want to extract information from XML you receive, so you can use the data in your application.

Solution

Use the methods of the Scala Elem and NodeSeq classes to extract the data. The most commonly used methods of the Elem class are shown here:

Scala: How to create XML literals

Problem: You want to create XML variables, and embed XML into your Scala code.

Solution

You can assign XML expressions directly to variables, as shown in these examples:

val hello = <p>Hello, world</p>
val p = <person><name>Edward</name><age>42</age></person>

In the REPL you can see that these variables are of type scala.xml.Elem:

A Scala XML XPath example

I'm not going to take any time to describe the following Scala XML/XPath example, other than to say that when it's run, it produces the following output, which is a simulated receipt for an order at a pizza store: