My Adventures in Coding

June 16, 2010

Working with XML in Scala: A Simple Example

Filed under: Conferences,Scala,UberConf 2010 — Brian @ 7:20 am
Tags: , , , ,

While at UberConf I had the great opportunity to attend a talk titled “Scala for Java Programmers” put on by Venkat Subramaniam, the author of the book “Scala Programming” . During the talk we went into a number of examples of where Scala excels over Java, in that it makes life for the developer significantly easier. One of those areas is in working with XML. In Scala, XML is a first class citizen (Woohoo!).

So for those of you who have never used Scala before, here are a few simple examples of working with XML:

Create XML
In this example all we do here is take some xml and assign it to a val. Okay, so does not seem like anything special, but wait, notice the lack of quotes around the XML tags.

val xml = <car make="Ford">Galaxy</car>

prints the XML:

<car make="Ford">Galaxy</car>

Generate XML
In this example we take a Map and generate XML based on the values in that Map.

val cars = Map("Galaxy" -> "Ford", "Chevelle" -> "Chevrolet")

def createCar() = { { entry =>
       val (key, value) = entry
       <car make={key}>{value}</car>

val xml = <cars>{createCar()}</cars>

prints the XML:

    <car make="Ford">Galaxy</car>
    <car make="Chevrolet">Chevelle</car>

Parse XML with Xpath

val xml = <car make="Ford">Galaxy</car>
val make = xml \\ "@make"

prints out the Result: Ford

Parsing XML From A Service
Alright, now let’s actually do something useful. The following is a simple example used by Venkat during his scala session. In this example we access Yahoo’s weather feed and return the City, State, and current temperature for Denver, CO.

import scala.xml._

val theUrl = ""

val xmlString = Source.fromURL(new URL(theUrl)).mkString
val xml = XML.loadString(xmlString)

val city = xml \\ "location" \\ "@city"
val state = xml \\ "location" \\ "@region"
val temperature = xml \\ "condition" \\ "@temp"
println(city + " " + state + " " + temperature)

Now, for fun, try writing this example in Java (Hmm, okay, that won’t be much fun at all).

To Run the examples

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at

%d bloggers like this: