XML Scala: How to manipulate your XML data with Scala

xml declarationXML is the Extensible Markup Language. Its use is to store and transport data. Most of the websites in the Internet use XML today. To understand XML you should have a basic understanding of HTML and JavaScript. XML defines a set of rules for encoding document in a format which is both machine readable and human readable. It is designed to be simple and widely used in the Internet. Many API’s provide functions to process XML data. Scala is being increasingly used with XML. To leverage the power of Scala you should be proficient with the native Scala XML API. In this intermediate level tutorial, we assume that you know the basics of XML and Scala. If you want to brush up the concepts of XML, we suggest that you take this introductory course on XML programming.

Introduction to Scala

Scalable Language or Scala is an object oriented language. In it, every value is an object and every operation is a method call. It provides native support for several traditional design patterns in other languages. There is support for advanced component architectures through classes and traits.

Scala is a full-fledged functional language. This language includes first-class functions and a library with efficient immutable data structures. Scala runs on the Java Virtual Machine (JVM). Note that Java and Scala classes can be freely mixed even if they reside on different projects. The Scala compiler incorporates a subset of a Java compiler. All the Java Libraries, frameworks and tools are available for this language. Scala runs on Android and on all common JVMs.

Functions in Scala are treated as objects. A notable feature of Scala is that it is suited for scalable server software. It makes good use of concurrent and synchronous processing, and distributed processing in the cloud.

To get a more in depth understanding of Scala, you can take this awesome course on Scala for developers.

Mapping in Scala

Scala Map is a collection of key-value pairs. To retrieve any value we need its key and these keys are unique. However, values need not be unique. Maps come in two kinds, mutable and immutable. When an object is immutable, it itself cannot be altered. Scala uses the immutable map by default.

XML Processing in Scala

Scala is used to create, parse and process XML documents. XML data is represented in Scala either by a generic data representation or data-specific data representation. Scala can process XML literals. In other words, it is not needed to put quotes around XML strings. You can write the strings directly and Scala will interpret them as XML element of type scala.xml.Element.

While running these examples please follow the sequence below:

  • Download Scala from http://www.scala-lang.org/downloads.
  • Add the Scala bin folder to your path.
  • Save the example to a file:Filename.scala.
  • Run the example: scala Filename.scala.

Lets go through a simple XML program, written in Scala.

Example 1: XML Program

      <title>Hello Scala XML</title>
      <h1>Hello world</h1>
      <p><a href="http://abc.go.com/">Scala</a> talks on Scalable Language</p>

This simple XML document can also be created using Scala. Take a look at the Scala program below

Example 2: XML in Scala Program

object XMLExample1 extends Application {
  val page =
      <title>Hello Scala XML</title>
      <h1>Hello world</h1>
      <p><a href="http://abc.go.com/">Scala</a>talks on Scalable Language </p>

In this program, Val in Scala declares an object to be a variable. The application trait quickly turns objects into executable programs. The variable page is initialized to the XML document. The tostring() function converts the variable  page content into a string. Then the println() function outputs the string on to the screen.

It is possible to mix Scala and XMl. Take a look at the programs below. The three programs use the same  example.

Example 3.1:  Program to Print XML Using Scala

val xmltest = <car make="Hyundai">Verna</car>
The output is XML code:
<car make="Hyundai">Verna</car>

In this program, we declare XMLtest to be a variable. We assign, some xml content to its value. Println() is a Scala function which displays the string on the output device. Note that there are no quotes in the output.

Example 3.2: Program to Generate XML

val cars1 = Map("Hyundai" -> "Verna", "Nissan" -> "Micra")
def createCar1() = {
   cars1.map { entry =>
       val (key, value) = entry
       <car make={key}>{value}</car>
val xml = <cars1>{createCar1()}</cars>

Below is the output:

    <car make="Hyundai">Verna</car>
    <car make="Nissan">Micra</car>

Def defines class properties with or without parentheses and with or without the equal sign. In this program, we take a Map and generate XML based on the values in that Map. The key is the make of the car while the value is the model of the car.

Example 3.3: Program to Parse XML with Xpath

val xml = <car make="Hyundai">Verna</car>
val make = xml \\ "@make"

Prints out the Result: Hyundai

The variable which has xml value is parsed here.

Example 4: Parsing XML From A Service

import scala.xml._
import java.net._
import scala.io.Source
val theUrl = "https://www.google.com/#q=weather+forecast+san+francisco"
val newString = Source.fromURL(new URL(theUrl)).mkString
val xml = XML.loadString(newString)
 val newcity1 = xml \\ "location" \\ "@city"
val newstate1 = xml \\ "location" \\ "@region"
val newtemperature1 = xml \\ "condition" \\ "@temp"
 println(newcity1 + " " + newstate1 + " " + newtemperature1)

In this example we access Google’s weather forecast and return the City, State, and current temperature for San Francisco, CA. Import function includes the different functions available in various packages. LoadString() function retrieves the string. We parse the retrieved string for the values of city, region and temperature. These values are assigned to the corresponding variables. Finally, the values of the variables are printed on the screen.

You will find that programming in Scala is fun. You may even find it easy if you have a Java programming background (if not, you may want to take this beginners course to Java Programming). Using Scala with XML can be leveraged to create useful and exciting programs. The more you program, the better you become at programming. This tutorial assumes that you are conversant with both XML and Scala. You can advance your knowledge by taking this course on Web Programming from scratch. This will give you a good feel of how HTML, XML and Scala work together.