xmlgroovystreamingmarkupbuilder

Groovy StreamingMarkupBuilder output XML separator


I'm currently using in my groovy script the StreamingMarkupBuilder to produce my output XMl. Works all pretty well but when I have multiple elements with the same name in the source message, do I have an option to add separatos?

<Organisation>
   <Name>Name1</Name>
   <Name>Name2</Name>
   <Name>Name3</Name>
</Organisation>`

I use it in the following way:

builder.OrganisationName{
   NameFormatted Organisation.Name.toString() 
}

In my output I receive:

<NameFormatted>
   Name1Name2Name3
</NameFormatted>

I want to receveive the following - each element separated by blank or pre-defined separater

<NameFormatted>
  Name1 Name2 Name3
</NameFormatted>

Does anybody have a tip for me?

Thanks Marco


Solution

  • Please try in the following way:

    import groovy.util.XmlSlurper
    import groovy.xml.StreamingMarkupBuilder
    import groovy.xml.XmlUtil
    
    def slurped = new XmlSlurper().parseText('''<Organisation>
       <Name>Name1</Name>
       <Name>Name2</Name>
       <Name>Name3</Name>
    </Organisation>''')
    
    println slurped.Name
    
    def builder = new StreamingMarkupBuilder()
    def output = builder.bind {
        OrganisationName {
            NameFormatted slurped.Name.join(' ')
        }
    }
    println XmlUtil.serialize(output)
    

    Other separators can also be passed to join instead of space.