XmlSlurper将所有xml元素返回到地图中

时间:2014-11-12 09:17:21

标签: groovy

我有以下groovy代码:

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)

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

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

感谢。

1 个答案:

答案 0 :(得分:11)

你可以摆动递归武器。 ;)

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']
]
相关问题