Skip to Content
Technical Articles
Author's profile photo Akash Ashok

Convert flat file into XML

Taking a stroll in Question and Answers section of SAP Cloud Platform Integration Tools, i did spot a issue which seemed to be quite common.

How do we convert a flat file into XML without complicating the process.

Well to start off with, achieving a small task might seem to be complicated in middleware ; if you think it is bad with SAP CPI you need to visit SAP PI/PO then

But to make our life easier SAP has aided Groovy scripts within the Integration Design so that we could enhance the iFlow.

So the below Groovy script would help you to convert the flat file into needed XML format.

Let us consider the sample text format, which i supplied into my Groovy through content modifier : (ignore the coding box)

11111111111111111111111111111       +1X1X1X1X1X    SSSSSS - ABC Primary
22222222222222222222222222222       +2Y2Y2Y2Y2Y    SSSSSS - ABC Primary
33333333333333333333333333333       +2Y2Y2Y2Y2Y    SSSSSS - ABC Primary


expected out to be

<node3>SSSSSS - ABC Primary</node3>
<node3>SSSSSS - ABC Primary</node3>
<node3>SSSSSS - ABC Primary</node3>


Groovy Script:

import java.util.HashMap;
import groovy.xml.MarkupBuilder

def Message processData(Message message) {
       def body = message.getBody(java.lang.String)as String;
	   def varStringWriter = new StringWriter();
	   def varXMLBuilder   = new MarkupBuilder(varStringWriter);
	   String newItem ;
			line -> newItem = line ;
			String newItem1 = newItem.substring(0,29).trim();
                        String newItem2 = newItem.substring(30,47).trim();
                        String newItem3 = newItem.substring(52,72).trim();

		def xml = varStringWriter.toString();
		xml="<RECORDS>"+xml+"</RECORDS>" ;

       return message;


So having the data sent to the Groovy and with this base we can achieve what seems to be a cumbersome task

On other hand if you would need spaces to be recorded on your XML nodes then please remove .trim() ; since trim() removes the empty space.

Hope this helped

Assigned Tags

      1 Comment
      You must be Logged on to comment or reply to a post.
      Author's profile photo Nisha Divakaran
      Nisha Divakaran

      Hi Akash Ashok,

      This article was very informative. I have a requirement in which i need to identify the first 2 characters of the text file and build the XML tag based on that character value.

      for example if the first two characters in 02, then the offset 03(10) will be in tag <orderno>.

      Is this possible?