How to process XML using Scala

There are many ways to process xml using scala and there many libraries available for the task. In this task i will show a simple approach i have used. This example uses scala 2.13.1

On a high level the objectives are load the XML then find the interested node and extract information from it. For this example, the XML will be a hard coded string.

package com.stackrules

import scala.xml.XML
//Example - Extract information from xml 
object XmlParser extends App {

  val xmlString =
    """
      |<order>
      |  <item>
      |    <title>iphone</title>
      |    <color>black</color>
      |  </item>
          <item>
      |    <title>ipad</title>
      |    <color>white</color>
      |  </item>
      |</order>
      |""".stripMargin

  //load the xml using XML class
  val xml = XML.loadString(xmlString)

  // Process the xml and extract title from all item nodes
  val itemTitle = (xml \\ "item" \ "title")
  itemTitle.map(t=>t.text).foreach(println);
}

In this example i have used scala.xml library. To include this library add the dependency to the build.sbt. Here is how i have added it in build.sbt

libraryDependencies ++= Seq(
 "org.scala-lang.modules" %% "scala-xml" % "2.0.0-M1"
)

You can get more details of the Scala XML by visiting the Git for the same – Scala XML Git

Leave a Comment