groovy 将参数传递给StreamingMarkupBuilder的闭包

olqngx59  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(144)

Groovy 2.4,Spring5.3.13
使用StreamingMarkupBuilder创建一些XML、序列化并打印它时运气不佳

public void createMsgToStreamOut( String strCreatedAt, String strEntity, String strIdNum, String strEvent) {
    def streamBuilder = new StreamingMarkupBuilder();
    streamBuilder.encoding = "UTF-8"
    def xml = streamBuilder.bind{ strCreatedAt, strEntity, strIdNum, strEvent -> 
        >> some magic goes here
    }
    def xmlStr = XmlUtil.serialize( xml)
    println xmlStr;
}

createMsgToStreamOut( "2022-09-10T12:13:14.567", "Matter", "907856", "create");

应给予

<?xml version="1.0" encoding="UTF-8"?>
<message>
  <timestamp>2022-09-10T12:13:14.567</timestamp>
  <entity>Matter</entity>
  <number>907856</number>
  <event>create</event>
</message>

下一步是将输出流传输到Kafka制作者。

b4wnujal

b4wnujal1#

我想你要找的魔法是这样的:

def xml = streamBuilder.bind {
    message {
        timestamp(strCreatedAt)
        entity(strEntity)
        number(strIdNum)
        event(strEvent)
    }
}

下面是完整的工作脚本:

import groovy.xml.*

createMsgToStreamOut( "2022-09-10T12:13:14.567", "Matter", "907856", "create");

void createMsgToStreamOut(String strCreatedAt, String strEntity, String strIdNum, String strEvent) {
    def streamBuilder = new StreamingMarkupBuilder();
    streamBuilder.encoding = "UTF-8"
    def xml = streamBuilder.bind {
        message {
            timestamp(strCreatedAt)
            entity(strEntity)
            number(strIdNum)
            event(strEvent)
        }
    }
    def xmlStr = XmlUtil.serialize( xml)
    println xmlStr;
}

如果有帮助就告诉我。

相关问题