Scala 将 XML 导入到 map

标签 scala dictionary xml-parsing

我刚刚学习 scala,正在尝试将 XML 文件导入到 map 中。 XML 使用 <word></word> 保存定义和<description></description> 。当我尝试创建 map 时出现错误:

Value update is not member of scala.collection.immutable.Map[String, String]

如有任何指点,我们将不胜感激!

    package main
import scala.xml._

object main {

  def main(args: Array[String]): Unit = {
    val definitions = XML.load("src\\main\\Definitions.xml");
    val definitionMap = (Map[String, String]() /: (definitions \ "word")) { (map , defNode) =>
        val word = (defNode \ "word").text.toString()
        val description = (defNode \ "description").text.toString()
        map(word) = description
    }
    println(definitions.getClass())
    println("Number of elements is " + (definitions \\ "word").size)
  }

}

XML 的格式如下:

<?xml version="1.0"?>
<definitions>
    <entry>
        <word>Ontology</word>
        <description>A set of representational primitives with which to model a domain of knowledge or discourse.</description>
    </entry>

    <entry>
        <word>Diagnostic</word>
        <description>The process of locating problems with software, hardware, or any combination thereof in a system, or a network of systems.</description>
    </entry>
    <entry>
        <word>Malware</word>
        <description>Software that is intended to damage or disable computers and computer systems.</description>
    </entry>
    <entry>
        <word>Capacitor</word>
        <description>A device used to store an electric charge, consisting of one or more pairs of conductors separated by an insulator.</description>
    </entry>
    <entry>
        <word>Stress Test</word>
        <description>A test measuring how a system functions when subjected to controlled amounts of stress.</description>
    </entry>
    <entry>
        <word>Registry</word>
        <description>A hierarchical database that stores configuration settings and options on Microsoft Windows operating systems.</description>
    </entry>
    <entry>
        <word>Antivirus</word>
        <description>Designed to detect and remove computer viruses.</description>
    </entry>
</definitions>

最佳答案

你不能改变不可变的数据结构,这就是编译器想说的。而不是更新,

map(word) = description

您应该不断向 map 添加记录。

map + (word -> description)

关于Scala 将 XML 导入到 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9383293/

相关文章:

java - 我想将 excel 转换为 xml

scala - 为什么 Scala 的类型推断不如 Haskell 强大?

scala - 在类型别名中使用上下文绑定(bind)

c# - C# Dictionary 在 C# in depth 2nd Edition 中是如何使用的?

java - 从 HashMap 中提取一个元素并更新它

dictionary - groovy 中的 bool 方法总是返回 true

c# - 如何在 C# 中对 XmlDocument 中的元素的子元素进行排序?

scala - Scala 的 Map.unzip 返回的原因 (Iterable, Iterable)

scala - Scala中Any和String之间的类型不匹配

java - Java中基于外部xml的运行时类实例化