xmlgroovymarkupbuilder

call function during xml traversal in groovy


I transform one xml to another and I am not able to call function defined on script level from closure which used to process node from input xml. See example code

def xml = new MarkupBuilder()

def text ='''
<x>
    <y id='1'/>
    <y id='2'/>
</x>
'''
def x = new XmlSlurper().parseText(text)

String generateId(String s) {
// some code 
}

xml.root() {
    x.y.each {
        a(id: generateId(it.@id))
    }
}

Output:

<root>
  <generateId>1</generateId>
  <a id='generateId' />
  <generateId>2</generateId>
  <a id='generateId' />
</root> 

As you can see function generateId() is not called but node with name generateId is written to output xml.

I suppose it is MarkupBuilder which steps in and handles call but how can I walk around it?


Solution

  • You need to get the text() of the id attribute:

    String generateId(String s) {
        'generated ' + s
    }
    
    xml.root() {
        x.y.each {
            a(id: generateId(it.@id.text()))
        }
    }