royki
royki

Reputation: 1693

Scala - Getting the error scala.xml.NodeSeq

I am trying to write code to import XML file. I am missing some basic things -- Here is the code.

import xml._

case class Menu(name: List[String])
case class BreakFastMenu(food: List[Menu], price: List[Menu], des: List[Menu], cal: List[Menu])

def toMenu(node : Node): Menu = {
    val menuChart = (node \ "food")
    Menu(menuChart)
}

def toBreakFastMenu(node: Node): BreakFastMenu = {
    val name = (node \ "name").map(toMenu).toList
    val price = (node \ "price").map(toMenu).toList
    val des = (node \ "description").map(toMenu).toList
    val cal = (node \ "calories").map(toMenu).toList
    BreakFastMenu(name, price, des, cal)
}

val menuXML = XML.loadFile("simple.xml")
val food = (menuXML \ "food").map(toBreakFastMenu).toArray
food.foreach(println)

And the XML file is here - simple.xml Getting the error as

MenuXML.scala:9: error: type mismatch;
 found   : scala.xml.NodeSeq
 required: List[String]
        Menu(menuChart)
             ^
one error found

Can anyone sort me out what the basics I am missing .

Upvotes: 1

Views: 1138

Answers (1)

Balint Pato
Balint Pato

Reputation: 1549

You are mixing up the types. Menu takes List[String] and not scala.xml.NodeSeq.

You get the error, because you are passing the whole node (scala.xml.NodeSeq), not just the content of it.

I can recommend this blogpost to review for further explanation: http://alvinalexander.com/scala/how-to-extract-data-from-xml-nodes-in-scala

I would recommend to get your representation right first always. The best way to organize your case classes is to match the structure of the nodes. E.g. in case of a <food> node, you'd probably want to introduce a Food class.

  import xml._

  case class Food(food: String, price: String, des: String, cal: String)
  case class BreakFastMenu(foodItems: List[Food])

  def toFood(node : Node): Food = {        
    val name = (node \ "name").text
    val price = (node \ "price").text
    val des = (node \ "description").text
    val cal = (node \ "calories").text
    Food(name, price, des, cal)
  }


  val menuXML = XML.load("http://www.w3schools.com/xml/simple.xml")
  val breakFastMenu = BreakFastMenu((menuXML \ "food").map(toFood).toList)
  breakFastMenu.foodItems.foreach(println)

Upvotes: 1

Related Questions