Ok, I saw your problem now. I simplify it to this to show you the solution:
xml = '''
<Results>
<ResultSet>
<Row>
<TRANSACTION_ID>123</TRANSACTION_ID>
<TRANSACTION_DATE_KEY>20182103</TRANSACTION_DATE_KEY>
</Row>
<Row>
<TRANSACTION_ID>456</TRANSACTION_ID>
<TRANSACTION_DATE_KEY>20182003</TRANSACTION_DATE_KEY>
</Row>
</ResultSet>
</Results>'''
class Model {
def transactionId
def transactionDate
def buildJdbcData(row) {
transactionId = row.TRANSACTION_ID
transactionDate = row.TRANSACTION_DATE_KEY
}
}
new XmlSlurper().parseText(xml).ResultSet.Row.collect { new Model().buildJdbcData(it) }
The problem is that your "constructor" method isn't really a constructor. It's basically doing this:
groovy.slurpersupport.NodeChildren buildJdbcData(row) {
transactionId = row.TRANSACTION_ID
transactionDate = row.TRANSACTION_DATE_KEY
return transactionDate
}
That's because a method with no return statement will always return the last thing it evaluated. What you probably meant was:
Model buildJdbcData(row) {
transactionId = row.TRANSACTION_ID
transactionDate = row.TRANSACTION_DATE_KEY
return this
}
That gets us closer to the solution, but it's still not quite going to solve your problem.
a = new XmlSlurper().parseText(xml).ResultSet.Row.collect { new Model().buildJdbcData(it) }
b = new XmlSlurper().parseText(xml).ResultSet.Row.collect { new Model().buildJdbcData(it) }
assert a != b
But they should be the same right? Well since you haven't defined what Model.equals(Model) means, it's just coming back with "a is b", i.e. whether they are the same object, in this case they are not. You can fix it like this:
...
boolean equals(Model other) {
(this.transactionId == other.transactionId) &&
(this.transactionDate == other.transactionDate)
}
}
and now
assert a==b
But that's tedious for a lot of properties... instead I would just recommend that you do away with the whole Model class, and use a Map. A Map comes with Map.equals(Map) already defined.
import groovy.json.JsonSlurper
xml = '''
<Results>
<Row>
<transactionId>123</transactionId>
<transactionDate>20182103</transactionDate>
</Row>
<Row>
<transactionId>456</transactionId>
<transactionDate>20182003</transactionDate>
</Row>
</Results>'''
json = '''
{
"Row": [{
"transactionId":"123",
"transactionDate":"20182103"
}, {
"transactionId":"456",
"transactionDate":"20182003"
}]
}'''
fromXml = new XmlSlurper().parseText(xml)
.Row.collect { [transactionId: it.transactionId, transactionDate: it.transactionDate] }
fromJson = new groovy.json.JsonSlurper().parseText(json)
.Row.collect { [transactionId: it.transactionId, transactionDate: it.transactionDate] }
assert fromXml == fromJson