简体   繁体   中英

Groovy script to transform xml to json

I have the following groovy script that transforms an xml into json.

https://stackoverflow.com/a/24647389/2165673

Here is my xml

<?xml version="1.0" encoding="utf-8"?>
<Response xmlns="">
<ProgressResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ErrorMessage>error   </ErrorMessage>
<IsSuccessful>false</IsSuccessful>
</ProgressResult>
</ProgressResponse>

The JSON result i need is

{
"IsSuccessful" : "false",
"ErrorMessage" : "Something Happened"
}

but i am getting the following http://www.tiikoni.com/tis/view/?id=b4ce664

I am trying to improve my groovy script but i just started using it and it has a steep learning curve. Can someone help direct me to the right direction?

Thanks!!

Should just be (untested, but should work):

def map = new XmlParser().parseText(xml)
   .MarkInProgressResult
   .with { x ->
    [IsSuccessful: x.IsSuccessful.text(),
     ErrorMessage: x.ErrorMessage.text()]
}
String json = new JsonBuilder(map)

Your xml is short and easy. This could be help you :

In java:

public class Util {

    public static String getTagValue(String xml, String tagName){
        return xml.split("<"+tagName+">")[1].split("</"+tagName+">")[0];
    }

}

In groovy component:

def jsonBuilder = new groovy.json.JsonBuilder()
jsonBuilder(
    IsSuccessful: Util.getTagValue(xml,"IsSuccessful"),
    ErrorMessage: Util.getTagValue(xml,"ErrorMessage")
)

return jsonBuilder.toPrettyString()

Here the project:

https://github.com/jrichardsz/mule-esb-usefull-templates/tree/master/simple-json-groovy

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