我正在尝试编写代码来导入XML文件。我遗漏了一些基本的东西 - 这是代码。
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)
XML文件在这里 - simple.xml 获取错误
MenuXML.scala:9: error: type mismatch;
found : scala.xml.NodeSeq
required: List[String]
Menu(menuChart)
^
one error found
任何人都可以解释我缺少的基本知识。
答案 0 :(得分:1)
你正在混淆这些类型。菜单采用List [String]而不是scala.xml.NodeSeq。
您收到错误,因为您传递的是整个节点(scala.xml.NodeSeq),而不仅仅是它的内容。
我可以推荐此博客文章进行审核,以获得进一步的解释:http://alvinalexander.com/scala/how-to-extract-data-from-xml-nodes-in-scala
我建议首先让你的代表权正确。组织案例类的最佳方法是匹配节点的结构。例如。如果是<food>
节点,您可能想要引入一个Food类。
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)