convert any csv file as xml file using groovy script


sname,sno,smarks

t,3,234

abc,1,234

a,3,234

r,4,234

b,5,44444

---------------
<?xml version="1.0" encoding="UTF-8"?><root>
  <record>
    <sname>a</sname>
    <sno>3</sno>
    <smarks>234</smarks>
  </record>
  <record>
    <sname>b</sname>
    <sno>5</sno>
    <smarks>44444</smarks>
  </record>
  <record>
    <sname>r</sname>
    <sno>4</sno>
    <smarks>234</smarks>
  </record>
  <record>
    <sname>t</sname>
    <sno>3</sno>
    <smarks>234</smarks>
  </record>
</root>









import com.sap.gateway.ip.core.customdev.util.Message;

import java.util.HashMap;

import groovy.xml.XmlUtil


def Message processData(Message message) {

    //Body 

    def body = message.getBody(String);


    def lines = body.trim().split('\n')

    

   

    

    def headers = lines[0].split(',')

    def data = lines[1..-1]  // not splitting here, i want to sort lines using logic after this i will apply split;

      //sorting logic

data.sort { line1, line2 ->

    def value1 = line1.split(',')[0] as String

    def value2 = line2.split(',')[0] as String

    value1 <=> value2

}


// Convert the array to an ArrayList

def myList = new ArrayList(data)


// Loop through the ArrayList using a for loop and display its elements

for (int i = 0; i < myList.size(); i++) {

   // println(myList.get(i))

    if(myList.get(i).contains("abc"))

    myList.remove(i)

}


data=myList.collect { it.split(',') }  // convert arraylist to array and split;

    def xml = new StringBuilder()


    xml.append('<root>')

    data.each {

        row ->

            xml.append('<record>')

        headers.eachWithIndex {

            header,

            index ->

            xml.append("<${header}>${row[index]}</${header}>")

        }

        xml.append('</record>')

    }

    xml.append('</root>')


    def formattedXml = XmlUtil.serialize(xml.toString())


    message.setBody(formattedXml)

    return message;

}



https://blogs.sap.com/2023/06/07/simplifying-data-transformation-convert-csv-to-xml-with-sap-cpi-and-groovy/

Popular posts from this blog

pss book : శ్రీకృష్ణుడు దేవుడా, భగవంతుడా completed , second review needed. 26th April 2024

pss book: గురు ప్రార్థనామంజరి . completed 21st july 2024

pss book: కధల జ్ఞానము read review pending. 25th june 2024