groovymarkupbuilderstreamingmarkupbuilder

passing in args to a Closure for a StreamingMarkupBuilder


Groovy 2.4, Spring 5.3.13

Not having much luck using StreamingMarkupBuilder to create some XML, serialize it and print it

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");

should give

<?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>

next step is to stream the output to a Kafka producer.


Solution

  • The magic you're looking for looks like that, I suppose:

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

    Here is the fully working script:

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

    Let me know if it helps.