Groovy Examples

Go to list of examples

Convert XML to CSV (Manual)

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.

Script

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()
	message.setBody(ag.execute(body))
	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))	
		writer.close()
	}
}

Input Body

<?xml version="1.0" encoding="utf-8"?>
<Root>
	<Headers>
		<string>FirstName</string>
		<string>LastName</string>
		<string>Title</string>
		<string>Birthdate</string>
	</Headers>
	<Items>
		<string>Marley</string>
		<string>Paige</string>
		<string>Senior Robot</string>
		<string>1999-06-07Z</string>
	</Items>
		<Items>
		<string>Laurel</string>
		<string>Meyer</string>
		<string></string>
		<string>2002-06-07Z</string>
	</Items>
		<Items>
		<string>Gabe</string>
		<string>Meyer</string>
		<string>Senior Robot</string>
		<string>1982-06-07Z</string>
	</Items>
</Root>

Expected Result Body

FirstName,LastName,Title,Birthdate
Marley,Paige,Senior Robot,1999-06-07Z
Laurel,Meyer,,2002-06-07Z
Gabe,Meyer,Senior Robot,1982-06-07Z