XML processing in Scala part 3

Wed, Nov 13, 2013

Programming Scala #programming #scala

We’ve learned how to read XML in part 1 and some useful classes to process XML in part 2, this blog will show you how to traverse the XML nodes.

Here is the sample codes.

object Main extends Application {
//First we will define some XML nodes and assign to a variable.
val xml = {
  <h1>Title Found!!</h1><div><a href="">My site</a></div><a href="http://www.google.com">Google</a>

// to access any h1 element in the xml, we will use the \ method followed by the tag name we want to locate.
println(xml \ "h1")
// output : Title Found!!

// by default, \ method will return a list of XML Nodes, so we can process it like a list
// Here is how we get the first element in the list of Nodes we located 
val title = (xml \ "h1").headOption
// if the first element is None, then it will print out "No title found"
println(title.getOrElse("No title found"))

// To print every <a> in the XML
xml \ "a" foreach println

// To print every <div> in the XML
xml \ "div" foreach println

// To print only <a> inside <div> tag
xml \ "div" \ "a" foreach println

xml \ "div" \ "a" foreach(link => {
  // To get the text node of the XML element
  // To get the attribute of the XML element, we will need to use an @
  println(link \ "@href")