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-na开发者_如何学运维me 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?
xml \ "field" map { x => ((x \ "@name").text -> x) } toMap
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.
Both posted answers yield a map, but to get a Map[String, Node] you must call (x \ "@name").text
to get the attribute value.
精彩评论