从 scala.xml.NodeSeq 创建一个 Map
我有以下 xml 节点:
val xml = <fields><field name="one"></field><field name="two"></field></fields>
现在我想创建一个以字段名称作为键的 Map[String, Node]。
for{x <- xml \ "field"} yield Map(x \ "@name" -> x)
使用上面的yield,我得到了一个地图列表:
List(Map((one,<field name="one"></field>)), Map((two,<field name="two"></field>)))
如何在功能上获取地图[String,Node],而不采用命令式方式(临时变量)将列表中的地图转换为最终所需的地图,也许没有收益?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想有一种更简单的方法可以做到这一点,但
应该可行。您基本上会生成一系列元组,然后将其转换为 Map。
I guess there is an yet easier way to do this, but
should work. You basically yield a sequence of tuples and convert it to a Map afterwards.
两个发布的答案都会生成一个地图,但要获取 Map[String, Node],您必须调用
(x \ "@name").text
来获取属性值。Both posted answers yield a map, but to get a Map[String, Node] you must call
(x \ "@name").text
to get the attribute value.