ChanChow
ChanChow

Reputation: 1366

How to append multiple strings in Groovy?

I am parsing an XML file in Groovy and later I need to append the variables returned.

def lmList = slurperResponse.LastGlobal.HeatMap
String appendedString = lmList.country + lmList.ResponseTime + lmList.timeset

This doesn't work to append the 3 strings. It just assigns the first string to the right. How to properly implement it in Groovy? I tried concat and it threw the following error:

groovy.lang.MissingMethodException: No signature of method: groovy.util.slurpersupport.NodeChildren.concat() is applicable for argument types: (groovy.util.slurpersupport.NodeChildren) values: [4468]
Possible solutions: toFloat(), collect(), collect(groovy.lang.Closure)
at 

Upvotes: 1

Views: 7066

Answers (3)

dmahapatro
dmahapatro

Reputation: 50275

Assuming the xml looks like:

def xml = '''
<Root>
    <LastGlobal>
        <HeatMap>
            <Country>USA</Country>
            <ResponseTime>20</ResponseTime>
            <TimeSet>10</TimeSet>
        </HeatMap>
    </LastGlobal>
</Root>
'''

Below should give what is expected:

def slurped = new XmlSlurper().parseText(xml)
assert slurped.LastGlobal.HeatMap.children()*.text().join() == 'USA2010'

Upvotes: 1

BZ.
BZ.

Reputation: 1946

As an alternative to injecteer -

def lmList = slurperResponse.LastGlobal.HeatMap
String appendedString = lmList.country.toString() + lmList.ResponseTime.toString() + lmList.timeset.toString()

You weren't trying to add strings, you were trying to add nodes the happen to contain strings.

Upvotes: 1

injecteer
injecteer

Reputation: 20707

Yor code shall look like:

String appendedString = "${lmList.country}${lmList.ResponseTime}${lmList.timeset}"

The exception you are getting means, that you are trying to invoke the plus()/concat() method which is not provided by NodeChildren

Upvotes: 2

Related Questions