trajectory
trajectory

Reputation: 1509

create a 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 key.

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

Using yield above I get a List of Maps though:

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

How do I functionally get a Map[String, Node] without going the imperative way (temp-vars) to transform the Maps in the List to the final desired Map, maybe without yield?

Upvotes: 3

Views: 2816

Answers (3)

The Archetypal Paul
The Archetypal Paul

Reputation: 41749

  xml \ "field" map { x => ((x \ "@name").text -> x) } toMap

Upvotes: 5

hbatista
hbatista

Reputation: 1237

Both posted answers yield a map, but to get a Map[String, Node] you must call (x \ "@name").text to get the attribute value.

Upvotes: 2

soc
soc

Reputation: 28413

I guess there is an yet easier way to do this, but

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

should work. You basically yield a sequence of tuples and convert it to a Map afterwards.

Upvotes: 4

Related Questions