Create map from scala.xml.NodeSeq

I have the following xml- node:

val xml = <fields><field name="one"></field><field name="two"></field></fields>

Now I would like to create a Map [String, Node] with the field name as the key.

for{x <- xml \ "field"} yield Map(x \ "@name" -> x)

Using the output above, I get a list of maps, though:

List(Map((one,<field name="one"></field>)), Map((two,<field name="two"></field>))) 

How can I functionally get the [String, Node] map without switching to the imperative mode (temp-vars) to convert the Maps in the List to the final desired map, possibly without a lesson?

+3
source share
3 answers
  xml \ "field" map { x => ((x \ "@name").text -> x) } toMap
+5
source

I assume there is an even simpler way to do this, but

(for{x <- xml \ "field"} yield (x \ "@name", x)).toMap

must work. You basically get a sequence of tuples and then convert them to a map.

+4
source

, [String, Node], (x \ "@name").text, .

+2

Source: https://habr.com/ru/post/1785443/


All Articles