mithun venkatesh
mithun venkatesh

Reputation: 3

xml to json conversion in Groovy

I need help with converting an xml to json in Groovy. The xml I have is something like this

 def xmlrecords = '''<root>
                        <node1>abc</node1>
                        <node2>def</node2>
                        <node3>hij</node3>
                        </root>'''

I know this is fairly simple, but I'm struggling to get to grips with groovy. So any help would be very much appreciated.

Thanks.

UPDATE

I know that I can do something like

def xml= new XmlParser().parseText( xmlrecords )
def json = new JsonBuilder()

json.records
{
   node1 "abc"
   node2 "def"
   node3 "hij"
}

println json.toPrettyString()

but what I want to do is access the data of the nodes like this

json.records
    {
       node1 xml.node1   //xml.node1=abc
       node2 xml.node2
       node3 xml.node3
    }

since the data that each node stores keeps changing for me. Whatever code that I have written above doesn't work and I have been breaking my head over this. So Could you please help me out?

Upvotes: 0

Views: 2527

Answers (2)

CodeMonkey
CodeMonkey

Reputation: 23748

Direct XML to JSON conversion can create ugly deeply-nested JSON. You need to transform the XML into the simplified structure you want in the JSON.

def xmlrecords = '''<root>
                        <node1>abc</node1>
                        <node2>def</node2>
                        <node3>hij</node3>
                    </root>'''
def xml= new XmlParser().parseText( xmlrecords )

// programmatically transform XML into Map with node name and value
def map = new TreeMap()
xml.each {
 map.put(it.name(), it.text())
}

def json = JsonOutput.toJson(map)
println JsonOutput.prettyPrint(json)

The JSON output:

{
    "node1": "abc",
    "node2": "def",
    "node3": "hij"
}

Upvotes: 0

Naz
Naz

Reputation: 141

You're pretty much on the right track. You just needed to apply the .text() function on your xml object.

See below

static main(args) {

    def xmlrecords = '''<root>
                    <node1>abc</node1>
                    <node2>def</node2>
                    <node3>hij</node3>
                    </root>'''

    def xml= new XmlParser().parseText(xmlrecords)
    def json = new JsonBuilder()

    json.records
    {
       node1 xml.node1.text()  //xml.node1=abc
       node2 xml.node2.text()
       node3 xml.node3.text()
    }

    println json.toPrettyString()
}

Output

{
"records": {
    "node1": "abc",
    "node2": "def",
    "node3": "hij"
    }
}

Hope this helps!

Upvotes: 2

Related Questions