Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlSlurper to return all xml elements into a map

Tags:

groovy

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.

like image 821
nzsquall Avatar asked Nov 12 '14 09:11

nzsquall


People also ask

What is XML slurper?

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.

What is groovy XmlSlurper?

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.

How do I read XML content in groovy?

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.


1 Answers

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']
]
like image 132
dmahapatro Avatar answered Oct 14 '22 10:10

dmahapatro