Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
Showing results for 
Search instead for 
Did you mean: 


This blog covers an idea on how we can convert a Flat File to dynamic XML structure with Field Fixed Lengths in CPI using groovy script.

Input Flat File Sample :

202310FABCDX    01TEST123 4530450801000100000002825999010152023
202310FABCDF 01TEST456 3530150801000100000014582444010152023
202310FABCDA 01TEST789 5530250801000100000023264182710152023

Expected Output XML :

<?xml version="1.0" encoding="UTF-8"?>

Groovy Script

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

def Message processData(Message message)
def body = message.getBody(java.lang.String) as String;
def lines = body.split("\n");

//root node
def body1 = "<Root>";

//Get the XML segments name and Field fixed lengths
def prop = message.getProperties();
def Segments = prop.get("xmlSegments").split(",") as String[]
def FieldFixedLengths = prop.get("FieldFixedLengths").split(",") as String[]

//looping to read the lines and form a XML
for (i = 0; i < lines.length; i++)
def sum = 0
body1 += "<Record>";

//looping through externalized parameters to create XML tag with fixed lengths
for (k = 0; k < FieldFixedLengths.length; k++)
def l2 = Integer.valueOf(FieldFixedLengths[k]);

println("Start" + sum + "End" + l2)

body1 += "<" + Segments[k] + ">" + lines[i].substring(sum, sum + Integer.valueOf(FieldFixedLengths[k])) + "</" + Segments[k] + ">";
sum += Integer.valueOf(FieldFixedLengths[k]);
body1 += "</Record>";
//closing root note
body1 += "</Root>";

//storing the converted XML to body
return message;


Simulation results on online Groovy IDE :

Simulation Results for Flat File to XML with Field Fixed Length conversion

NOTE : Please pass xmlSegments and Field Fixed Lengths (with comma separated values) as Message Property through a Content Modifier

Pros : 

  • Dynamic names for XML segments can be generated as we are externalizing the XMLSegment names and their fixed field lengths.

Cons :

  • This groovy may be suitable when the data load and no of lines in the flat file is less. If the no of Line items is comparatively more, then chances are there that we may observe a performance issue (in terms of processing times of this script). By referring the link Handling text files in Groovy script of CPI (SAP Cloud Platform Integration). | SAP Blogs , the above groovy can be modified to read data as Input Stream instead of reading body as String for an optimal memory footprint.


Groovy script to convert Flat file to XML (with dynamic xml segment names) was illustrated above.

Comments or feedback/suggestions, pros/cons with respect to the above are welcome from fellow Integration folks.


Labels in this area