Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting XML to JSON in Groovy

I wish to convert xml to JSON using groovy. I understand the specifics of conversion is dependent on my preferences, but could someone please recommend which libraries and methods I should be using and provide me with a little information on why/how to use them? I am using groovy as I have been told it is a very effective parser, so I am looking for libraries that will take advantage of this

Thanks!

like image 431
Tom Hadkiss Avatar asked Sep 16 '13 14:09

Tom Hadkiss


1 Answers

I'm a bit late to the party, but the following code will convert any XML into a consistent JSON format:

def toJsonBuilder(xml){
    def pojo = build(new XmlParser().parseText(xml))
    new groovy.json.JsonBuilder(pojo)
}
def build(node){
    if (node instanceof String){ 
        return // ignore strings...
    }
    def map = ['name': node.name()]
    if (!node.attributes().isEmpty()) {
        map.put('attributes', node.attributes().collectEntries{it})
    }
    if (!node.children().isEmpty() && !(node.children().get(0) instanceof String)) { 
        map.put('children', node.children().collect{build(it)}.findAll{it != null})
    } else if (node.text() != ''){
        map.put('value', node.text())
    }
    map
}
toJsonBuilder(xml1).toPrettyString()

Converts the XML...

<root>
    <node>Tim</node>
    <node>Tom</node>
</root>

Into...

{
    "name": "root",
    "children": [
        {
            "name": "node",
            "value": "Tim"
        },
        {
            "name": "node",
            "value": "Tom"
        }
    ]
}

Feedback/improvements welcome!

like image 158
Nick Grealy Avatar answered Oct 06 '22 21:10

Nick Grealy