Skip to Content
Technical Articles

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

<RECORDS>
<RECORD>
<node1>11111111111111111111111111111</node1>
<node2>+1X1X1X1X1X</node2>
<node3>SSSSSS - ABC Primary</node3>
</RECORD>
<RECORD>
<node1>22222222222222222222222222222</node1>
<node2>+2Y2Y2Y2Y2Y</node2>
<node3>SSSSSS - ABC Primary</node3>
</RECORD>
<RECORD>
<node1>33333333333333333333333333333</node1>
<node2>+2Y2Y2Y2Y2Y</node2>
<node3>SSSSSS - ABC Primary</node3>
</RECORD>
</RECORDS>

 

Groovy Script:

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import java.io.File
import groovy.xml.MarkupBuilder

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

			varXMLBuilder.RECORD{
				node1(newItem1);
				node2(newItem2);
				node3(newItem3);
			}
		}
		def xml = varStringWriter.toString();
		xml="<RECORDS>"+xml+"</RECORDS>" ;

		message.setBody(xml);
        
       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

1 Comment
You must be Logged on to comment or reply to a post.
  • 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?