本文介绍了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元素返回到映射中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!