convert any csv file as xml file using groovy script
sname,sno,smarks
t,3,234
abc,1,234
a,3,234
r,4,234
b,5,44444
import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import groovy.xml.XmlUtil
def Message processData(Message message) {
//Body
def body = message.getBody(String);
def lines = body.trim().split('\n')
def headers = lines[0].split(',')
def data = lines[1..-1] // not splitting here, i want to sort lines using logic after this i will apply split;
//sorting logic
data.sort { line1, line2 ->
def value1 = line1.split(',')[0] as String
def value2 = line2.split(',')[0] as String
value1 <=> value2
}
// Convert the array to an ArrayList
def myList = new ArrayList(data)
// Loop through the ArrayList using a for loop and display its elements
for (int i = 0; i < myList.size(); i++) {
// println(myList.get(i))
if(myList.get(i).contains("abc"))
myList.remove(i)
}
data=myList.collect { it.split(',') } // convert arraylist to array and split;
def xml = new StringBuilder()
xml.append('<root>')
data.each {
row ->
xml.append('<record>')
headers.eachWithIndex {
header,
index ->
xml.append("<${header}>${row[index]}</${header}>")
}
xml.append('</record>')
}
xml.append('</root>')
def formattedXml = XmlUtil.serialize(xml.toString())
message.setBody(formattedXml)
return message;
}
https://blogs.sap.com/2023/06/07/simplifying-data-transformation-convert-csv-to-xml-with-sap-cpi-and-groovy/