I have the following groovy code:
def xml = '''<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<foot>
<email>[email protected]</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":"[email protected]","sig":"hello world"]]
Thanks.
XmlSlurper() Creates a non-validating and namespace-aware XmlSlurper which does not allow DOCTYPE declarations in documents. XmlSlurper(boolean validating, boolean namespaceAware) Creates a XmlSlurper which does not allow DOCTYPE declarations in documents.
Groovy's internal XmlParser and XmlSlurper provide access to XML documents in a Groovy-friendly way that supports GPath expressions for working on the document. XmlParser provides an in-memory representation for in-place manipulation of nodes, whereas XmlSlurper is able to work in a more streamlike fashion.
XML ParsingThe Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing.
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>[email protected]</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':'[email protected]', 'sig':'hello world']
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With