我有以下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"]]
感谢。
答案 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']
]