gpt4 book ai didi

groovy - XmlSlurper 将所有 xml 元素返回到映射中

转载 作者:行者123 更新时间:2023-12-02 06:25:19 26 4
gpt4 key购买 nike

我有以下常规代码:

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)

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

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

谢谢。

最佳答案

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

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']
]

关于groovy - XmlSlurper 将所有 xml 元素返回到映射中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26883223/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com