CPI Groovy Examples

Go to List of Examples

Convert XML to CSV (Manual)

CPI provides XML to CSV Converter which is documented here.

If you need to process XML, pick fields, do some further processing in a single step you can use this script. It doesn't escape "," be careful if your input can contain comma, and in general this is an error-prone way to generate CSV.

You should also check Convert XML to CSV (Apache Commons CSV)

This example also contains a class with main method. It is an idea to enable running the script on your computer with regular IDEs.


Try it on Groovy IDE
import com.sap.gateway.ip.core.customdev.util.Message;
import groovy.xml.*;

def Message processData(Message message) {
	def body = message.getBody(java.lang.String) as String;
	def ag = new xml2csv()
	return message

class xml2csv {
	def execute(ins) {
		//define writer 
		def writer = new StringWriter()
		//parse input
		def parsedXml = new XmlParser().parseText(ins)
		def content = new XmlSlurper().parseText(ins)
		def header = content.Headers.children().collect().join(',')
		def csv = content.Items.inject(header){ result, row ->
		 [result, row.children().collect().join(',')].join("\n")
		println csv.toString()
		return csv.toString()
	static main(args) {
		def ag = new xml2csv()
		def writer = new FileWriter("test/case1/output.csv")
		writer.write(ag.execute(new File("test/case1/input.xml").text))	

Input Body

<?xml version="1.0" encoding="utf-8"?>
		<string>Senior Robot</string>
		<string>Senior Robot</string>

Expected Result Body

Marley,Paige,Senior Robot,1999-06-07Z
Gabe,Meyer,Senior Robot,1982-06-07Z