XmlSlurper将所有xml元素返回到映射中 [英] XmlSlurper to return all xml elements into a map

查看:49
本文介绍了XmlSlurper将所有xml元素返回到映射中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下常规代码:

def xml = '''<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<foot>
    <email>m@m.com</email>
    <sig>hello world</sig>
</foot>
</note>'''

def records = new XmlSlurper().parseText(xml)

如何获取记录以返回地图,如下所示:

How do I get records to return a map looks like the following:

["to":"Tove","from":"Jani","heading":"Reminder","body":"Don't forget me this weekend!","foot":["email":"m@m.com","sig":"hello world"]]

谢谢.

推荐答案

您可以摆动递归武器. ;)

You can swing the recursion weapon. ;)

def xml = '''<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<foot>
    <email>m@m.com</email>
    <sig>hello world</sig>
</foot>
</note>'''

def slurper = new XmlSlurper().parseText( xml )

def convertToMap(nodes) {
    nodes.children().collectEntries { 
        [ it.name(), it.childNodes() ? convertToMap(it) : it.text() ] 
    }
}

assert convertToMap( slurper ) == [
    'to':'Tove', 
    'from':'Jani', 
    'heading':'Reminder', 
    'body':"Don't forget me this weekend!", 
    'foot': ['email':'m@m.com', 'sig':'hello world']
]

这篇关于XmlSlurper将所有xml元素返回到映射中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆