【问题标题】:Groovy script to transform xml to json将 xml 转换为 json 的 Groovy 脚本
【发布时间】:2015-09-23 17:57:54
【问题描述】:

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

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

这是我的 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 脚本,但我刚开始使用它,它的学习曲线很陡峭。有人可以帮我指引正确的方向吗?

谢谢!!

【问题讨论】:

标签: json xml groovy mule


【解决方案1】:

应该只是(未经测试,但应该可以工作):

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

【讨论】:

    【解决方案2】:

    您的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      • 2014-12-30
      相关资源
      最近更新 更多