Groovy 将 xml 转换为 json 的脚本

Groovy script to transform xml to json

我有以下 groovy 脚本,可将 xml 转换为 json。

这是我的 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>

我需要的 JSON 结果是

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

但我得到以下信息 http://www.tiikoni.com/tis/view/?id=b4ce664

我正在尝试改进我的 groovy 脚本,但我才刚刚开始使用它,而且它的学习曲线很陡。有人可以帮我指引正确的方向吗?

谢谢!!

应该是(未经测试,但应该有效):

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

您的 xml 简短易懂。这可能对你有帮助:

在java中:

public class Util {

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

}

在 groovy 组件中:

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

return jsonBuilder.toPrettyString()

这里是项目:

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