下面是我的XML。我想创建一个Map[String,String]
,其中键是单元格中的第一个,值是第二个值,例如Map["Active" -> "A","Cancelled"->"c"......]
<?xml version="1.0" encoding="UTF-8" ?>
<dvm name="Mapping" xmlns="http://xmlns.oracle.com/dvm">
<description>
</description>
<columns>
<column name="XXXX"/>
<column name="YYYY"/>
</columns>
<rows>
<row>
<cell>Active</cell>
<cell>A</cell>
</row>
<row>
<cell>Cancelled</cell>
<cell>C</cell>
</row>
<row>
<cell>Suspended</cell>
<cell>S</cell>
</row>
<row>
<cell>Reserved</cell>
<cell>R</cell>
</row>
<row>
<cell>N/A</cell>
<cell>N</cell>
</row>
</rows>
</dvm>
答案 0 :(得分:0)
如果你的xml是用如下代码定义的(请注意你并不是真的想要第一行):
val xml = //<?xml version="1.0" encoding="UTF-8" ?>
<dvm name="Mapping" xmlns="http://xmlns.oracle.com/dvm">
<description>
...
然后您可以使用以下代码段将其转换为地图:
val map = ((xml \\ "row") map { row =>
val pair = row \ "cell" map { cell =>
cell.text
}
pair(0) -> pair(1)
}).toMap
答案 1 :(得分:0)
val table =
<dvm name="Mapping" xmlns="http://xmlns.oracle.com/dvm">
<description>
</description>
<columns>
<column name="XXXX"/>
<column name="YYYY"/>
</columns>
<rows>
<row>
<cell>Active</cell>
<cell>A</cell>
</row>
<row>
<cell>Cancelled</cell>
<cell>C</cell>
</row>
<row>
<cell>Suspended</cell>
<cell>S</cell>
</row>
<row>
<cell>Reserved</cell>
<cell>R</cell>
</row>
<row>
<cell>N/A</cell>
<cell>N</cell>
</row>
</rows>
</dvm>
val cells = for ( row <- table \\ "row") yield (for (cell <- row \ "cell" ) yield cell.text) match {
case Seq(k,v) => (k,v)
}
cells.toMap
答案 2 :(得分:0)
这是最简单的方法,假设示例XML文件是dvm.xml
。
val dvm: scala.xml.Elem = scala.xml.XML.loadFile("dvm.xml")
val rows: Seq[Seq[String]] = {
for {
rows <- dvm \ "rows"
row <- rows \ "row"
} yield {
for {
cell <- row \ "cell"
} yield {
cell.text
}
}
}
val cells: Seq[(String, String)] =
for ( Seq(k, v) <- rows )
yield (k -> v)
val mappings: Map[String, String] = cells.toMap
val a: String = mappings("Active")
val c: String = mappings("Cancelled")
val r: String = mappings("Reserved")
val n: String = mappings("N/A")
这是故意快速和肮脏的。如果您想处理没有两个单元格元素或其他各种错误条件的情况,您应该开始一个新问题并询问,并提供您使用的源代码。
这是scala-xml wiki,其中包含更多示例,现在: