简体   繁体   中英

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?

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!

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM